在64位操作系统中,所有类型的指针都是8字节。
在32位操作系统中,所有类型的指针都是4字节。
对于const char *str[]={"aa","bbb" ,"1234567890"};,它的每个元素都是一个char*指针,所以它的每个元素占8字节。即:
sizeof(str[0])==8;
sizeof(str)/sizeof(str[0])==3;
字符型char占1个字节
整型int占4个字节
长整型long int占8个字节
sizeof(char)==1
sizeof(int)==4
sizeof(long int)==8
但是,所有指针类型都是8字节:
sizeof(char*)==8
sizeof(int*)==8
sizeof(long int*)==8
以下是例子:
#include <iostream>
// g++ -std=c++11 -pthread test.cpp -o test
int main() {
const char *str[] = {"BLACK", "RED", "YELLOW",
"GREEN", "UNKNOWN", "123456789"};
unsigned int str_num = sizeof(str) / sizeof(str[0]);
std::cout << "sizeof(str[0]= " << sizeof(str[0]) << std::endl; //结果是 8
std::cout << "sizeof(str[5]= " << sizeof(str[5]) << std::endl; //结果是 8
std::cout << "sizeof(str)= " << sizeof(str) << std::endl; //结果是 6*8=48
std::cout << "sizeof(str)/sizeof(str[0])= " << str_num
<< std::endl; //结果是 48/8=6
char *p1 = nullptr;
int *p2 = nullptr;
long int *p3 = nullptr;
std::cout << "sizeof(p1)= " << sizeof(p1) << std::endl; //结果是 8
std::cout << "sizeof(char*)= " << sizeof(char *) << std::endl;
std::cout << "sizeof(int*)= " << sizeof(int *) << std::endl;
std::cout << "sizeof(p2)= " << sizeof(p2) << std::endl; //结果是 8
std::cout << "sizeof(p3)= " << sizeof(p3) << std::endl; //结果是 8
std::cout << "sizeof(char)= " << sizeof(char) << std::endl; //结果是 1
std::cout << "sizeof(int)= " << sizeof(int) << std::endl; //结果是 4
std::cout << "sizeof(long int)= " << sizeof(long int)
<< std::endl; //结果是 8
return 0;
}
本文探讨了64位操作系统中不同类型的指针大小均为8字节的现象,并通过示例代码验证了这一结论。同时介绍了字符型、整型、长整型等基本数据类型的大小。

6270

被折叠的 条评论
为什么被折叠?



