0 c arrays string pointers scanf
Segmentation fault (core dumped)
在 C 中,我初始化了一个字符串数组,如下所示:
char* strings[20];
Run Code Online (Sandbox Code Playgroud)
然后尝试了fscanf一堆东西。
for(int i = 0; i<20; i++){
fscanf(file, "%s", strings[i]);
}
Run Code Online (Sandbox Code Playgroud)
尽管该程序还有更多内容,但我确信这是导致分段错误的部分。使用 gdb 运行表明错误位于 file 中vfscanf,所以我认为这是相关的。
小智 5
声明后
char* strings[20]; // This is an array of pointer of type char *
Run Code Online (Sandbox Code Playgroud)
您需要为每个指针分配内存,然后才能从文件中读取它们。
for(int i = 0; i<20; i++){
strings[i] = malloc(some_size * sizeof(char)); // allocate memory for each pointer first.
fscanf(file, "%s", strings[i]);
}
Run Code Online (Sandbox Code Playgroud)