您的位置:首页 > 其它

strlen和sizeof的区别(续一)

2011-04-14 13:18 148 查看
本文通过几段小程序来学习strlen和sizeof的区别

  1 #include <stdio.h>

  2 #include <stdlib.h>

  3 #include <string.h>

  4

  5 int main()

  6 {

  7     char str[15];

  8    

  9     printf("strlen(str) = %d, sizeof(str) = %d/n", strlen(str), sizeof(str)     ); 

 10    

 11     strcpy(str, "www.it315.org");       // 共13个字符

 12    

 13     printf("str = %s/n", str);

 14     printf("strlen(str) = %d, sizeof(str) = %d/n", strlen(str), sizeof(str)     ); 

 15    

 16     char *pstr;

 17    

 18     printf("strlen(pstr) = %d, sizeof(pstr) = %d, sizeof(*pstr) = %d/n", str    len(pstr), sizeof(pstr), sizeof(*pstr) );

 19    

 20     pstr = (char *)malloc(30 * sizeof(char) );

 21     memset(pstr, 0, 30 * sizeof(char) );

 22     strcpy(pstr, "http://www.it315.org");       // 共20个字符

 23    

 24     printf("pstr = %s/n", pstr);

 25     printf("strlen(pstr) = %d, sizeof(pstr) = %d, sizeof(*pstr) = %d/n", str    len(pstr), sizeof(pstr), sizeof(*pstr) );

 26    

 27     free(pstr);

 28     return 0;

 29 }

 

程序的输出如下:

strlen(str) = 6, sizeof(str) = 15

str = www.it315.org

strlen(str) = 13, sizeof(str) = 15

strlen(pstr) = 8, sizeof(pstr) = 4, sizeof(*pstr) = 1

pstr = http://www.it315.org
strlen(pstr) = 20, sizeof(pstr) = 4, sizeof(*pstr) = 1

 

可以得出如下结论:

sizeof(str)表示的是字符数组str[15]所占的内存空间的大小,包括结尾的'/0';

sizeof(pstr)表示的是指针变量pstr所占内存空间的大小,是4位;

sizeof(*pstr)表示的是指针变量pstr所指向的字符所占的内存空间大小,字符是char型的,占1位。

sizeof表示相应的变量所分配的内存空间的大小,不受里面存储内容的改变的影响。

 

strlen才能代表实际的字符串长度,以'/0'结束,并且不包括结尾的'/0'。

未初始化的数组或指针,使用strlen是没有意义的。

 

还有下面的代码可以得到一些需要注意的结论

char

str[]=
"abcdef"
;

printf(
"%d/n"
,
sizeof
(
str));

printf(
"%d/n"
,
strlen(
str));

最终结果为:

7

6

char

sr[]

=

{
'a'
,
'b'
,
'c'
,
'd'
,
'e'
,
'f'
,'/0'};

printf(
"%d/n"
,
sizeof
(
sr));

printf(
"%d/n"
,
strlen(
sr));

最终结果为:

7

6

下面是神奇的时刻到来了:

char
sr[]
=
{
'a'
,
'b'
,
'c'
,
'd'
,
'e'
,
'f'
};

printf(
"%d/n"
,
sizeof
(
sr));

printf(
"%d/n"
,
strlen(
sr));

最终结果为:

6

12

当有限长数组存储字符时最后一位没有添加‘/0’的话,strlen的结论也是不可预测的。

 

  1 #include <stdio.h>

  2 #include <string.h>

  3

  4 int main()

  5 {

  6     struct X

  7     {

  8         int a;

  9         char b;

 10 //      char *c;

 11     };

 12     struct X x;

 13     printf("sizeof(X) = %d, sizeof(x) = %d/n", sizeof(struct X), sizeof(x) )    ;

 14     x.a = 4;

 15     x.b = 'z';

 16 //  x.c = "hello";

 17     printf("sizeof(x) = %d/n", sizeof(x) );

 18     return 0;

 19 }

得到的结果如下:

sizeof(X) = 8, sizeof(x) = 8

sizeof(x) = 8

这里涉及到数据对齐,在C++中的类也有类似的情况。


了CPU存取的速度最快(这同CPU取数操作有关,详细的介绍可以参考一些计算机
原理方面的书),在处理数据时经常把结构变量中的成员的大小按照4或8的倍数计算,这就叫数据对齐(data
alignment)。这样做可能会浪费一些内存,但理论上速度快了。当然这样的设置会在读写一些别的应用程序生成的数据文件或交换数据时带来不便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  alignment struct 存储 c