我有这个非常简单的C代码,它必须回显x数组中的值,令人惊讶的是,它还回应了数组中的值y...
#include <iostream.h>
#include <conio.h>
#include <string.h>
int i;
char x[3]={'a','b','c'},
y[3][2]={
{'a','A'},
{'b','B'},
{'c','C'}};
void main(){
clrscr();
while(i<strlen(x)) cout << x[i++] << endl;
getch();
}
Run Code Online (Sandbox Code Playgroud)
输出:
a
b
c
a
A
b
B
c
C
Run Code Online (Sandbox Code Playgroud)
显然,前3个字符是我真正打算回应的
那些... 但是那些跟随数组的字符怎么样y?
变量x不是字符串,调用strlen()它会导致未定义的行为.
访问超出数组的范围x也会导致未定义的行为.
你需要:
const char *x = "abc";
Run Code Online (Sandbox Code Playgroud)
使它成为有效的字符串(即被终止'\0'),或:
const char x[] = { 'a', 'b', 'c', '\0' };
Run Code Online (Sandbox Code Playgroud)
但那更加冗长,为什么要这样做呢?如果你的意思是一个字符串(你做),把它写成一个字符串.
您当然可以采用其他方式,并说"它是一个字符数组,但不是字符串",但是您不能使用strlen()哪个需要字符串:
const char x[] = { 'a', 'b', 'c' };
for(size_t i = 0; i < sizeof x / sizeof *x; ++i)
printf("%c\n", x[i]);
Run Code Online (Sandbox Code Playgroud)