【C++】20. const char *str[]、指针的字节长度等 分析
生活随笔
收集整理的這篇文章主要介紹了
【C++】20. const char *str[]、指针的字节长度等 分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在64位操作系統中,所有類型的指針都是8字節。
在32位操作系統中,所有類型的指針都是4字節。
對于const char *str[]={"aa","bbb" ,"1234567890"};,它的每個元素都是一個char*指針,所以它的每個元素占8字節。即:
字符型char占1個字節
整型int占4個字節
長整型long int占8個字節
但是,所有指針類型都是8字節:
sizeof(char*)==8 sizeof(int*)==8 sizeof(long int*)==8以下是例子:
#include <iostream> // g++ -std=c++11 -pthread test.cpp -o testint 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; //結果是 8std::cout << "sizeof(str[5]= " << sizeof(str[5]) << std::endl; //結果是 8std::cout << "sizeof(str)= " << sizeof(str) << std::endl; //結果是 6*8=48std::cout << "sizeof(str)/sizeof(str[0])= " << str_num<< std::endl; //結果是 48/8=6char *p1 = nullptr;int *p2 = nullptr;long int *p3 = nullptr;std::cout << "sizeof(p1)= " << sizeof(p1) << std::endl; //結果是 8std::cout << "sizeof(char*)= " << sizeof(char *) << std::endl;std::cout << "sizeof(int*)= " << sizeof(int *) << std::endl;std::cout << "sizeof(p2)= " << sizeof(p2) << std::endl; //結果是 8std::cout << "sizeof(p3)= " << sizeof(p3) << std::endl; //結果是 8std::cout << "sizeof(char)= " << sizeof(char) << std::endl; //結果是 1std::cout << "sizeof(int)= " << sizeof(int) << std::endl; //結果是 4std::cout << "sizeof(long int)= " << sizeof(long int)<< std::endl; //結果是 8return 0; }總結
以上是生活随笔為你收集整理的【C++】20. const char *str[]、指针的字节长度等 分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Socket网络编程】17. recv
- 下一篇: 【C++】34. gflags中的 --