用c++编在程序中先声明int,float,char,double型的变量,再声明 int,rloat,char,double类型的指针变量,并用相应存储空间初始化指针变 量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少宇 节。(提示用sizeof运算符)
时间: 2024-02-03 09:14:38 浏览: 82
以下是代码实现:
#include <iostream>
using namespace std;
int main() {
int a = 10;
float b = 3.14;
char c = 'A';
double d = 2.71828;
int* ptr1 = &a;
float* ptr2 = &b;
char* ptr3 = &c;
double* ptr4 = &d;
cout << "Size of int pointer: " << sizeof(ptr1) << endl;
cout << "Size of float pointer: " << sizeof(ptr2) << endl;
cout << "Size of char pointer: " << sizeof(ptr3) << endl;
cout << "Size of double pointer: " << sizeof(ptr4) << endl;
cout << "Size of int variable pointed by ptr1: " << sizeof(*ptr1) << endl;
cout << "Size of float variable pointed by ptr2: " << sizeof(*ptr2) << endl;
cout << "Size of char variable pointed by ptr3: " << sizeof(*ptr3) << endl;
cout << "Size of double variable pointed by ptr4: " << sizeof(*ptr4) << endl;
return 0;
}
输出结果:
Size of int pointer: 8
Size of float pointer: 8
Size of char pointer: 8
Size of double pointer: 8
Size of int variable pointed by ptr1: 4
Size of float variable pointed by ptr2: 4
Size of char variable pointed by ptr3: 1
Size of double variable pointed by ptr4: 8
解释:
sizeof
运算符返回变量或类型所占用的字节数。int
,float
,char
,double
分别占用 4 字节、4 字节、1 字节、8 字节。- 指针变量占用 8 字节(因为我的机器是 64 位的)。
- 指针变量所指向的变量占用的字节数与变量类型相同。
相关推荐

















