用C++在程序中先声明int,float,char,double型的变量,再声明int,float,char,double类型的指针变量,并用相应存储空间初始化指针变量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少字节。
时间: 2023-08-14 22:08:20 浏览: 102
以下是示例代码:
```cpp
#include <iostream>
int main() {
int i = 0;
float f = 0.0f;
char c = 'a';
double d = 0.0;
int* iptr = &i;
float* fptr = &f;
char* cptr = &c;
double* dptr = &d;
std::cout << "Size of int pointer: " << sizeof(iptr) << " bytes" << std::endl;
std::cout << "Size of float pointer: " << sizeof(fptr) << " bytes" << std::endl;
std::cout << "Size of char pointer: " << sizeof(cptr) << " bytes" << std::endl;
std::cout << "Size of double pointer: " << sizeof(dptr) << " bytes" << std::endl;
std::cout << "Size of int pointed by int pointer: " << sizeof(*iptr) << " bytes" << std::endl;
std::cout << "Size of float pointed by float pointer: " << sizeof(*fptr) << " bytes" << std::endl;
std::cout << "Size of char pointed by char pointer: " << sizeof(*cptr) << " bytes" << std::endl;
std::cout << "Size of double pointed by double pointer: " << sizeof(*dptr) << " bytes" << std::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 int pointer: 4 bytes
Size of float pointed by float pointer: 4 bytes
Size of char pointed by char pointer: 1 bytes
Size of double pointed by double pointer: 8 bytes
```
在这个示例程序中,我们首先声明了一个 `int`、`float`、`char` 和 `double` 类型的变量,并分别初始化为 0、0.0、'a' 和 0.0。然后,我们声明了一个 `int*`、`float*`、`char*` 和 `double*` 类型的指针变量,分别用 `&` 运算符获取对应变量的地址进行初始化。
在输出部分,我们使用 `sizeof` 运算符获取指针变量和指针变量所指的变量的大小,并输出。可以看到,所有指针变量的大小都是 8 字节(64 位系统),而指针变量所指的变量的大小分别是 4、4、1 和 8 字节。这是因为 `int` 和 `float` 类型占 4 字节,`char` 类型占 1 字节,而 `double` 类型占 8 字节。
阅读全文