桑海

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 数组做sizeof的参数不退化,传递给strlen就退化为指针;
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 //#define PE(x) printf("sizeof("); printf(#x") = %d\n", sizeof(x))
 5 
 6 void func(char str[100])
 7 {
 8     printf("func(sizeof(str) = %d)\n", sizeof(str));
 9 }
10 int main()
11 {
12     char str[] = "hello";
13     char *p = str;
14     int n = 10;
15     void *q = malloc(100);
16 /*
17     PE(str);
18     PE(p);
19     PE(n);
20     */
21     /*
22     char [],字符数组,OS自动在字符数组末尾追加'\0',
23     作为字符数组大小的一部分,即占一个字节的内存。
24     但是,并不作为字符数组有效长度的一部分。strlen是以'\0'
25     为标志。即char str[] = "hello",内存6,长度5
26     */
27     printf("sizeof(str) = %d\n", sizeof(str));  //字符数组大小 sizeof(str) = 6
28     printf("strlen(str) = %d\n", strlen(str));  //
29     printf("sizeof(p) = %d\n", sizeof(p));      //一个指针的大小4个字节   sizeof(p) = 4
30     printf("strlen(p) = %d\n", strlen(p));      //
31     printf("sizeof(*p) = %d\n",sizeof(*p));     //第一个字符,sizeof(p) = 1
32     printf("sizeof(n) = %d\n", sizeof(n));      //sizeof(n) = 4
33     char s[100];
34     func(s);               //函数字符数组以头指针形式传递形参   sizeof(s) = 4
35     printf("sizeof(*q=malloc(100)) = %d\n", sizeof(p));//一个指针占4字节
36     return 0;
37 }
sizeof(char [])

 

 

定义字符数组时,系统会自动在末尾补上字符串结束标志字符'\0',并一起存到字符数组中,

 

几点说明:

①字符串结束标志'\O'仅用于判断字符串是否结束,输出字符串时不会输出。

②在对有确定大小的字符数组用字符串初始化时,数组长度应大于字符串长度。如:

char s[7]={ "program};

由于数组长度不够,结束标志符'\O'未能存人s中,而是存在s数组之后的一个单元里,这可能会破坏其他数据,应特别注意。可以改为:

char s[8]={ "program};

 

strcpy()字符串str2中的\O也一起拷贝

 

(4)字符串长度函数strlen()

函数原型:unsigned int strlen(char *str);

调用格式:strlen(字符串);

函数功能:求字符串的实际长度(不包括'\O'),由函数值返回。例如:

static char s[10]= "student";

int len:

len=strlen(s);

len的值为7,而strlen("good")函数值为4。

 

posted on 2013-10-30 18:17  桑海  阅读(756)  评论(0编辑  收藏  举报