我正在玩C和scanf功能,并遇到了这个奇怪的错误,我似乎无法弄清楚.给出以下代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a;
} sample;
void fn(sample *s) {
char command;
scanf("%[abc]", &command);
printf("Read: %c\n", command);
printf("In the sample function:, %i\n", s->a);
}
int main() {
sample *s = malloc(sizeof(sample));
s->a = 4;
printf("Before sample function: %i\n", s->a);
fn(s);
printf("After sample function: %i\n", s->a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这似乎是错误的.随着输出:
$ ./sample
Before sample function: 4
a
Read: a
In the sample function:, 4
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)
我用了gdb并附加了一个watch结构,看来在scanf函数内部,它似乎在"修改"结构体?这很奇怪,因为即使在 …