关于char数组初始化的一些细节

  1. #include<stdio.h>  
  2. #include<string.h>  
  3. int main()  
  4. {  
  5.     int i;  
  6.     char s[100];  
  7.     memset((void *)s,0,100);  
  8.     if(s == NULL)  
  9.     {  
  10.         printf("s==NULL;s=%s;/n",s);  
  11.     }  
  12.     else   
  13.     {  
  14.         printf("s!=NULL;s=%s;/n",s);  
  15.     }  
  16.     for(i =0;i<100;i++)  
  17.     {  
  18.         printf("s[%d]=%c;",i,s[i]);  
  19.     }  
  20.     printf("/n");  
  21.     printf("len=%d/n",strlen(s));  
  22.     printf("sizeof=%d/n",sizeof(s));  
  23.     return 0;  
  24. }  
 

1

char数组全部初始化为0后,数组名s并不等于NULL。如果后面用来存取一个字符串时,判断是否读取成功,要用strlen,不能与NULL作比较。

2

char s[100]={0}效果与后面的memset((void *)s,0,100);一样,全部初始化为0。但是要注意char s[100]={'a'};只初始化了s[0]='a',其他的全部为0.如果不做任何初始化的话,数组的内容不确定。

原文地址:https://www.cnblogs.com/hzcya1995/p/13318650.html