关于sizeof && strlen

本文深入探讨了C++中sizeof运算符的使用,包括对不同数据类型、数组和指针的处理方式,解释了sizeof如何返回类型或变量的实际字节数,并通过实例演示了其在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include
#include
using namespace std;

enum MyEnum
{
a=0,
b=1,
EVO_MSG_REQUEST_IDENTIFIER_ALLOCATE = 3,
EVO_MSG_REPLY_IDENTIFIER_ALLOCATE = 4,

EVO_MSG_REQUEST_GRAPH_LIBRARY_QUERY = 5,
EVO_MSG_REPLY_GRAPH_LIBRARY_QUERY = 6

}MyEnum;

struct EvoVersion
{
char type;
char state;
char major;
char minor;
bool operator==(const EvoVersion & theVersion) const
{
return (type == theVersion.type
&& state == theVersion.state
&& major == theVersion.major
&& minor == theVersion.minor);
}
};

char m_CompName[128];
int main()
{

char *tmpBufMsg = new	char[100];
strcpy_s(tmpBufMsg,7, "hello");

cout << sizeof(tmpBufMsg) << endl;  //4
cout << strlen(tmpBufMsg) + 1 <<endl; //6

cout << sizeof(MyEnum) << endl;//4
cout << sizeof(a) << endl;//4


cout << sizeof(EvoVersion) << endl; //4
cout << sizeof(m_CompName) << endl; //128

unsigned int tt = 1;
cout << sizeof(tt) << endl; //4

unsigned long hh = 2;
cout << sizeof(hh) << endl; //4

system("pause");
return 1;

}

对sizeof的认知:

//对于非指针类型的数组,sizeof(数组名)长度是数组分配的大小,而不是数据类型所占的字节大小

char sz[] = "hello world!";
cout << "sizeof(sz)=" << sizeof(sz) << endl;      //13 带有结束符
cout << "sizeof(char)=" << sizeof(char) << endl;  //1个字节
cout << "sizeof sz=" << sizeof sz << endl;        //13
cout << "sz =" << sz << endl;                     //hello world!

char str[8];
cout << "sizeof(str)=" <<sizeof(str)<< endl;       //不是1 而是8
cout << "szieof(char)" << sizeof(char) << endl;    //1
cout << "str=" << str << endl;                     //烫烫烫烫烫烫烫烫

int a = 7;
cout << "a=" << a<<endl;                         //7
cout << "sizeof(a)=" << sizeof(a) << endl;            //4
cout << "sizeof(int)=" << sizeof(int) << endl;          //4





//指针类型的数据 为四个字节  不论是(char *)、(int *)还是(void *)都是四个字节
char* msg = new char[1024];
cout << "sizeof(char*)" << sizeof(char*) << endl;  //4
cout << "sizeof(msg)=" << sizeof(msg) << endl;     //4
cout << "msg=" << msg << endl;                     //1024个屯

int* msgTest = new int [1024];
cout << "sizeof(int*)" << sizeof(int*) << endl;          //4
cout << "sizeof(msgTest)=" << sizeof(msgTest) << endl;    //4
cout << "msgTest=" << msgTest << endl;       //0100BCA0 指向内存的地址

short i = 0;
cout << sizeof(short) << endl; //2
cout << sizeof(i) << endl; //2

bool flag = true;
cout << sizeof(bool) << endl; //1
cout << sizeof(flag) << endl; //1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值