用C++编写:在程序中先声明int,float,char,double型的变量,再声明int,float,char,double类型的指针变量,并用相应存储空间初始化指针变量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少字节。(提示用sizeof运算符)
时间: 2023-08-15 12:03:10 浏览: 86
下面是实现代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int i = 10;
float f = 3.14;
char c = 'A';
double d = 2.718;
int* pi = &i;
float* pf = &f;
char* pc = &c;
double* pd = &d;
cout << "The size of int pointer is: " << sizeof(pi) << " bytes" << endl;
cout << "The size of float pointer is: " << sizeof(pf) << " bytes" << endl;
cout << "The size of char pointer is: " << sizeof(pc) << " bytes" << endl;
cout << "The size of double pointer is: " << sizeof(pd) << " bytes" << endl;
cout << "The size of int variable pointed by pi is: " << sizeof(*pi) << " bytes" << endl;
cout << "The size of float variable pointed by pf is: " << sizeof(*pf) << " bytes" << endl;
cout << "The size of char variable pointed by pc is: " << sizeof(*pc) << " bytes" << endl;
cout << "The size of double variable pointed by pd is: " << sizeof(*pd) << " bytes" << endl;
return 0;
}
```
输出结果为:
```
The size of int pointer is: 8 bytes
The size of float pointer is: 8 bytes
The size of char pointer is: 8 bytes
The size of double pointer is: 8 bytes
The size of int variable pointed by pi is: 4 bytes
The size of float variable pointed by pf is: 4 bytes
The size of char variable pointed by pc is: 1 bytes
The size of double variable pointed by pd is: 8 bytes
```
可以看到,指针变量的大小都是8字节(64位系统),因为它们存储的是地址,而地址的大小与机器有关。而指针变量所指的变量大小分别是4字节、1字节和8字节,与它们的类型有关。
阅读全文