c++在程序中先声明int,float,char,double型的变量,再声明int,float,char,double类型的指针变量,并用相应存储空间初始化指针变量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少字节。
时间: 2023-08-14 17:08:20 浏览: 124
下面是示例代码:
```c++
#include <iostream>
using namespace std;
int main() {
int a = 0;
float b = 0.0f;
char c = 'a';
double d = 0.0;
int *p1 = &a;
float *p2 = &b;
char *p3 = &c;
double *p4 = &d;
cout << "Size of int pointer: " << sizeof(p1) << endl; // 输出指针变量占用的字节数
cout << "Size of float pointer: " << sizeof(p2) << endl;
cout << "Size of char pointer: " << sizeof(p3) << endl;
cout << "Size of double pointer: " << sizeof(p4) << endl;
cout << "Size of int variable: " << sizeof(*p1) << endl; // 输出指针变量所指的变量占用的字节数
cout << "Size of float variable: " << sizeof(*p2) << endl;
cout << "Size of char variable: " << sizeof(*p3) << endl;
cout << "Size of double variable: " << sizeof(*p4) << 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: 4
Size of float variable: 4
Size of char variable: 1
Size of double variable: 8
```
可以看出,不同类型的指针变量占用的字节数是相同的(这里是8个字节,因为我的电脑是64位系统),因为指针变量存储的是内存地址,而内存地址的字节数是固定的。而指针变量所指的变量的占用字节数则取决于变量类型。
阅读全文