sizeof的问题

VIPVIPVIP 2011-03-28 10:34:13

#include <iostream>
using namespace std;


void main(void)
{

char str1[]="aaaaa";
char str2[100];
char *p=str1;
char *buff = (char *)malloc(sizeof(char)*2);


//
cout<<"sizeof(str1):"<<sizeof(str1)<<endl;//字符串长度加1,6
cout<<"sizeof(*str1):"<<sizeof(*str1)<<endl;//输出结果为什么是1??取第一个元素吗?如果是,那么为什么sizeof(*str[2])是错误的
cout<<"sizeof(str2):"<<sizeof(str2)<<endl;//100
cout<<"sizeof(*str2):"<<sizeof(*str2)<<endl;//输出结果为什么是1?
cout<<"sizeof(p):"<<sizeof(p)<<endl;//指针
cout<<"sizeof(*p):"<<sizeof(*p)<<endl;
//

cout<<"sizeof(buff):"<<sizeof(buff)<<endl;
cout<<"sizeof(*buff):"<<sizeof(*buff)<<endl;//输出结果为什么是1??

strcpy(buff,"bbbbbbb");
cout<<"sizeof(*buff):"<<sizeof(*buff)<<endl;//输出结果为什么是1??
}


有些输出结果为什么是1??取第一个元素吗?如果是,那么为什么sizeof(*str[2])是错误的
...全文
65 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengzhixi 2011-03-28
  • 打赏
  • 举报
回复
cout<<"sizeof(*str1):"<<sizeof(*str1)<<endl;
*str1实际是第一个字符。字符的sizeof是1,*(str1+2)或者是str1[2]而不是*str1[2]

cout<<"sizeof(*str2):"<<sizeof(*str2)<<endl;
cout<<"sizeof(*buff):"<<sizeof(*buff)<<endl;//
同上

wei801516 2011-03-28
  • 打赏
  • 举报
回复
http://zhidao.baidu.com/question/3748023.html
楼主看看这个 该可以清楚了!~
bluewanderer 2011-03-28
  • 打赏
  • 举报
回复
sizeof如果里面是个表达式的话返回的是表达式的类型的尺寸。 *str1的类型是char,所以sizeof(*str1)等价于sizeof(char)

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧