用c++ 在程序中先声明int,rloat,char,double型的变量,再声明 int,float,char,double类型的指针变量,并用相应存储空问初始化指针变 量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少字 节。(提示用sizeof运算符)
时间: 2024-02-03 21:14:30 浏览: 23
下面是代码实现:
```cpp
#include <iostream>
using namespace std;
int main() {
int a = 1;
float b = 3.14;
char c = 'A';
double d = 2.718;
int* pa = &a;
float* pb = &b;
char* pc = &c;
double* pd = &d;
cout << "Size of int pointer: " << sizeof(pa) << " bytes" << endl;
cout << "Size of float pointer: " << sizeof(pb) << " bytes" << endl;
cout << "Size of char pointer: " << sizeof(pc) << " bytes" << endl;
cout << "Size of double pointer: " << sizeof(pd) << " bytes" << endl;
cout << "Size of int pointed by pointer: " << sizeof(*pa) << " bytes" << endl;
cout << "Size of float pointed by pointer: " << sizeof(*pb) << " bytes" << endl;
cout << "Size of char pointed by pointer: " << sizeof(*pc) << " bytes" << endl;
cout << "Size of double pointed by pointer: " << sizeof(*pd) << " bytes" << endl;
return 0;
}
```
输出结果为:
```
Size of int pointer: 8 bytes
Size of float pointer: 8 bytes
Size of char pointer: 8 bytes
Size of double pointer: 8 bytes
Size of int pointed by pointer: 4 bytes
Size of float pointed by pointer: 4 bytes
Size of char pointed by pointer: 1 bytes
Size of double pointed by pointer: 8 bytes
```
可以看出,指针变量在64位系统中占用8个字节,而指针所指向的变量占用的字节数分别为4、4、1和8,因为int、float和char类型在大多数机器上都是4字节对齐的,而double类型是8字节对齐的。