【语法】sizeof 笔记

本文通过C++代码示例展示了不同类型的字符串变量所占用的内存大小,包括标准库string类型及字符数组。对比了string对象与字符指针的大小差异,并分析了其原因。

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

 

 

 

#include <iostream>
#include 
<string>
using namespace std;

int main(int argc, char* argv[])
{
    cout 
<< "sizeof(string) = " << sizeof(string<< endl;
    
string str[] = {"sdf4""123""d"};
    
string str4[4= {"str33""mmmmm"};
    cout 
<< "sizeof(str) = " << sizeof(str) << endl;
    cout 
<< "sizeof(str4) = " << sizeof(str4) << endl;

    
string *pStr = new string[2];
    pStr[
0= "us";
    pStr[
1= "cn";
    cout 
<< endl;
    cout 
<< "sizeof(pStr) = " << sizeof(pStr) << endl;
    cout 
<< "sizeof(*pStr) = " << sizeof(*pStr) << endl;

    cout 
<< endl;
    
char b[] = "fcdg123";
    cout 
<< "b = " << b << endl;
    cout 
<< "sizeof(b) = " << sizeof(b) << endl;
    cout 
<< "*b = "<< *<< endl;
    cout 
<< "sizeof(*b) =" << sizeof(*b) << endl;

    cout 
<< endl;
    
char *= "fcdg123";
    cout 
<< "c = " << c << endl;
    cout 
<< "sizeof(c) = " << sizeof(c) << endl;
    cout 
<< "*c = "<< *<< endl;
    cout 
<< "sizeof(*c) =" << sizeof(*c) << endl;
    
return;
}

 

sizeof(string= 16
sizeof(str) = 48
sizeof(str4) = 64

sizeof(pStr) = 4
sizeof(*pStr) = 16

= fcdg123
sizeof(b) = 8
*= f
sizeof(*b) =1

= fcdg123
sizeof(c) = 4
*= f
sizeof(*c) =1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值