免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3497 | 回复: 3
打印 上一主题 下一主题

请问sizeof 与strlen的区别? [复制链接]

论坛徽章:
0
1 [报告]
发表于 2003-06-01 09:57 |显示全部楼层

请问sizeof 与strlen的区别?

我要是你,就这么写:

  1. #inlcude "string.h"

  2. void main(void)
  3. {
  4.           unsigned char    j;                 // 1
  5.           unsigned char    s1[10];        // 2

  6.           j = sizeof(s1);                      // 3
  7.           memset(s1,0x10,j);  // 4
  8.           while(1){}                                   // 5
  9. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2003-06-01 15:59 |显示全部楼层

请问sizeof 与strlen的区别?

因为你的程序完全错了,造成了溢出!
你在用memcpy的时候没有往s1里面拷,而是往&s1里面拷,怎么能对?全局变量不在栈里,所以幸免。

二者的区别很明显:
sizeof是一个算符,strlen是一个函数。
先别想那么多歪的邪的,建议马上重读谭浩强的《C语言》,把基础打牢再说。

论坛徽章:
0
3 [报告]
发表于 2003-06-03 17:15 |显示全部楼层

请问sizeof 与strlen的区别?

原帖由 "hjs6142" 发表:
我用的编译器下面两种情况:
char s1[4] = {1,2,3,4};
char s2[10];

memcpy(s2,s1,strlen(s1));与memcpy(&s2,&s1,strlen(&s1))
的结果都一样!我真的也一头雾水,也许它把&s1当成&s1[0]了,我是这么理解的。
   

这是巧合!
这么说吧:
如果定义:char str[n]
那么:sizeof str等于n
sizeof &str等于4
你的s1有4个元素,也就是当n=4的时候当然恰好一样了。

当str是数组名的时候,编译器把&str理解为&str[0]
所以结果恰好一样。

所以,程序的结果正确不代表逻辑正确。该怎么写就怎么写,不要使用太多的tricky,否则连你自己都会糊涂的。

论坛徽章:
0
4 [报告]
发表于 2003-06-03 20:08 |显示全部楼层

请问sizeof 与strlen的区别?

原帖由 "hjs6142" 发表:
<html>;\r\n"
"</html>;\r\n"
};

(1)sizeof(s1) = ?
(2)strlen(s1) = ?

谢谢!
   

You were right.
This kind of problems have not a certain answer since we use different compiler.
You defined a ONE dimension char array by splitting a long string into two parts. I'm not sure whether your syntax is legal on all compilers.
In gcc, at least, sizeof s1 is the memory size of s1[] stays (including \0)
strlen s1 is the string size of s1[] (excluding \0)
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP