C中char指针的行为

syn*_*gma 0 c pointers declaration char

我正在以下列格式从文件中读取字符串:N // string的长度abcdef //长度为N的字符串

像那样:

char necklace[400];
fin = fopen("file.in", "r");
fscanf(fin, "%d %s", &N, necklace);
char* left = &necklace[0];
char* right = &necklace[N-1];
Run Code Online (Sandbox Code Playgroud)

但是,当我char*在使用它们之前声明它时,它会给我编译错误:

char necklace[400];
char* left, right;   // this causes the problem

fin = fopen("file.in", "r");
fscanf(fin, "%d %s", &N, necklace);

left = &necklace[0];
right = &necklace[N-1];
Run Code Online (Sandbox Code Playgroud)

你能告诉我这个行为吗?

Gop*_*opi 6

正确的方法是:

char *left,*right;
Run Code Online (Sandbox Code Playgroud)

当你这样做

char *left,right;
Run Code Online (Sandbox Code Playgroud)

那你得到的是什么

char *left;
char right; /*This is not what you need you need *right but got right*/
Run Code Online (Sandbox Code Playgroud)

所以你看到了编译错误