在 c++中,指针变量的大小(单位:字节)是
时间: 2023-12-10 22:01:01 浏览: 179
在C语言中,指针变量的大小取决于计算机系统的架构和操作系统的位数。一般来说,在32位操作系统中,指针变量的大小为4个字节,而在64位操作系统中,指针变量的大小为8个字节。这是因为在32位系统中,内存地址是用32位来表示的,所以指针变量的大小也是32位,即4个字节;而在64位系统中,内存地址是用64位来表示的,因此指针变量的大小也是64位,即8个字节。因此,在C语言中,指针变量的大小通常为4或8个字节。当然,这只是一般情况,具体的大小还是要根据具体的系统来确定。
相关问题
用C++编写:在程序中先声明int,float,char,double型的变量,再声明int,float,char,double类型的指针变量,并用相应存储空间初始化指针变量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少字节。(提示用sizeof运算符)
下面是实现代码:
```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字节,与它们的类型有关。
c++在程序中先声明int,float,char,double型的变量,再声明int,float,char,double类型的指针变量,并用相应存储空间初始化指针变量,分别显示这些指针变量占了多少字节,指针变量所指的变量占了多少字节。
下面是示例代码:
```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位系统),因为指针变量存储的是内存地址,而内存地址的字节数是固定的。而指针变量所指的变量的占用字节数则取决于变量类型。
阅读全文