#有關字符數組的初始化的若干問題#
一、注意事項:
1.字符數組的初始化,初始化時賦予的自然是字符(要加單引號)。
2.賦予字符也可以通過賦予相應字符的ASCII碼(去掉單引號)或賦予字符串(只加雙引號)來進行。
3.對字符數組完全不進行初始化,則各元素隨機。
4.對字符數組進行不完全初始化,則從低地址(a[i]中i從0開始)到高地址逐個字符依次初始化,未被初始化的元素默認爲空(即'\0'),而不是隨機生成。
5.初始化時切勿超出字符數組長度。
6.初始化時{}內爲空,則默認爲該字符數組初始化全空(所有元素都是空字符'\0')
7.'\0'是空字符
二、代碼演示及說明
#include <stdlib.h>
{
int i=0;
char a[10]; /*字符數組不進行初始化,會隨機*/
char b[10]={}; /*初始化爲全空*/
char c[10]={0}; /*方式爲【用若干字符的ASCII碼逐一對字符數組進行初始化】未被初始化的元素爲空*/
char d[10]={'0'}; /*''中被看作用來初始化某元素的字符,方式爲【用若干字符逐一對字符數組進行初始化】未被初始化元素初始化爲空*/
char e[10]={"0"}; /*""中被看作用來初始化某些元素字符串,方式爲【用字符串直接對字符數組進行初始化】超出字符串長度的未被初始化元素初始化爲空*/
char c1[10]={0,33,34,35,36,37,38,39,40,41}; /*c1爲c數組的擴展*/
char d1[10]={'\0','!','\"','#','$','%','&','\'','\(','\)'}; /*d1爲d數組的擴展*/
char e1[20]={"\0,!,\",#,$,%,&,\',\(,\)."}; /*e1爲e數組的擴展*/
for(i=0;i<=8;i++)
printf("%c,",a[i]);
printf("%c.\n",a[9]);
for(i=0;i<=8;i++)
printf("%c,",b[i]);
printf("%c.\n",b[9]);
for(i=0;i<=8;i++)
printf("%c,",c[i]);
printf("%c.\n",c[9]);
for(i=0;i<=8;i++)
printf("%c,",d[i]);
printf("%c.\n",d[9]);
for(i=0;i<=8;i++)
printf("%c,",e[i]);
printf("%c.\n",e[9]);
for(i=0;i<=8;i++)
printf("%c,",c1[i]);
printf("%c.\n",c1[9]);
for(i=0;i<=8;i++)
printf("%c,",d1[i]);
printf("%c.\n",d1[9]);
for(i=0;i<=19;i++)
printf("%c",e1[i]);
return 0;
}
b[10] : , , , , , , , , , .
c[10] : , , , , , , , , , .
d[10] : 0, , , , , , , , , .
e[10] : 0, , , , , , , , , .
c1[10] : ,!,",#,$,%,&,',(,).
d1[10] : ,!,",#,$,%,&,',(,).
e1[20] : ,!,",#,$,%,&,',(,).
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.