问题是您使用的是 C 样式字符串,而 C 样式字符串以零结尾。
例如,如果您想使用 char 数组打印“alien”:
char mystring[6] = { 'a' , 'l', 'i', 'e' , 'n', 0}; //see the last zero? That is what you are missing (that's why C Style String are also named null terminated strings, because they need that zero)
printf("mystring is \"%s\"",mystring);
输出应该是:
我的字符串是“外星人”
回到你的代码,它应该是这样的:
int main(void)
{
char a_static[5] = {'q', 'w', 'e', 'r', 0};
char b_static[5] = {'a', 's', 'd', 'f', 0};
printf("\n value of a_static: %s", a_static);
printf("\n value of b_static: %s\n", b_static);
return 0;//return 0 means the program executed correctly
}
顺便说一句,你可以使用指针代替数组(如果你不需要修改字符串):
char *string = "my string"; //note: "my string" is a string literal
你也可以用字符串字面量初始化你的 char 数组:
char mystring[6] = "alien"; //the zero is put by the compiler at the end
另外:对 C 样式字符串(例如 printf、sscanf、strcmp、strcpy 等)进行操作的函数需要零才能知道字符串的结束位置
希望您从这个答案中学到了一些东西。