这导致分段错误。需要进行什么更正?
int main(void)
{
char a_static = {'q', 'w', 'e', 'r'};
char b_static = {'a', 's', 'd', 'f'};
printf("\n value of a_static: %s", a_static);
printf("\n value of b_static: %s\n", b_static);
}
所发布的代码有误:a_static
和b_static
应该被定义为数组。
纠正代码有两种方法:
您可以添加空终止符,使这些数组成为适当的C字符串:
#include <stdio.h>
int main(void) {
char a_static[] = { 'q', 'w', 'e', 'r', '\0' };
char b_static[] = { 'a', 's', 'd', 'f', '\0' };
printf("value of a_static: %s\n", a_static);
printf("value of b_static: %s\n", b_static);
return 0;
}
或者,printf
可以使用精度字段打印未以空字符结尾的数组的内容:
#include <stdio.h>
int main(void) {
char a_static[] = { 'q', 'w', 'e', 'r' };
char b_static[] = { 'a', 's', 'd', 'f' };
printf("value of a_static: %.4s\n", a_static);
printf("value of b_static: %.*s\n", (int)sizeof(b_static), b_static);
return 0;
}
.
后面给出的精度指定了从字符串中输出的最大字符数。它可以作为十进制数给出,也可以作为*
给出,并在char
指针之前作为int
参数提供。
char a_static = {'q', 'w', 'e', 'r'};
a_static
应该是 字符数组
,用于存储多个字符。像这样制作它
char a_static[] = {'q', 'w', 'e', 'r','\0'}; /* add null terminator at end of array */
char b_static[] = {'a', 's', 'd', 'f','\0'};
a_static
b_static
int main()
{
char a_static[] = {'q', 'w', 'e', 'r','\0'};
char b_static[] = {'a', 's', 'd', 'f','\0'};
printf("a_static=%s,b_static=%s",a_static,b_static);
return 0;
}
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);
输出应该是:
mystring 是 "alien"
回到你的代码,它应该长这样:
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 mystring[6] = "alien"; //the zero is put by the compiler at the end
另外:操作C风格字符串的函数(例如printf、sscanf、strcmp、strcpy等)需要零知道字符串何时结束
希望你从这个答案中学到了一些东西。
char *a_static
使用一个指针。 - user5063151