我有一个名为islands.txt的文件,内容为:
islandone
islandtwo
islandthree
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct island{
char *name;
struct island *previous;
} island;
void printIsland(island is){
printf("%s", is.name);
if(is.previous && is.previous->name[0] != '\0'){
printf("%s", is.previous->name);
}
}
int main(){
// the file to be read.
FILE *islandsFile = fopen("islands.txt","r");
// temporary location to store the name read from the file.
char name[40];
// temporary pointer to an island which has been already read for linking.
island *previousIsland;
while(fscanf(islandsFile,"%s",name) != EOF){
// allocate space for a new island and point to it with (*newIsland) pointer
island *newIsland =malloc(sizeof(island));
// assign name
newIsland->name = name;
// if previousIsland pointer is not null
// it means there is an island that was read before newIsland in the file
if(previousIsland){
// newIsland.previous should hold the address of this previously read island..
newIsland->previous = previousIsland;
}
// now previousIsland is the newIsland..
previousIsland = newIsland;
printIsland(*newIsland);
puts("");
}
fclose(islandsFile);
}
我对输出的期望是:
islandone
islandtwoislandone
islandthreeislandtwo
相反,我所得到的只是分段错误。我已经尝试了一切,但我被卡住了。我在哪里得到分段错误?我是C的新手,我不知道如何调试。
答案 0 :(得分:5)
是的,您还需要为名称分配内存。您只需为结构分配
typedef struct island{
char *name;
struct island *previous;
} island;
所以这个
// assign name
newIsland->name = name;
将指针指向您在堆栈上的数组,但是每次循环迭代都会是相同的地址。
代替做
之类的事情newIsland->name = strdup(name);
或者如果您愿意
newIsland->name = malloc( strlen( name ) + 1 );
strcpy( newIsland->name, name );
答案 1 :(得分:2)
这里有几个问题。除了CyberSpock提到的那些,您还有以下代码:
island *previousIsland;
while(fscanf(islandsFile,"%s",name) != EOF){
/* some code omitted */
if(previousIsland){
newIsland->previous = previousIsland;
}
previousIsland变量未初始化,if第一次可能为true,因此前一个指针指向无效内存。然后当你在printIsland中结束时,它将继续跟随未初始化的指针,进入无效的内存。我也看到你没有释放()任何记忆,但这可能是因为你不关心这么小的例子。
要调试C程序,调试器就是你的朋友。现在你不知道你使用的操作系统和编译器,但是如果你使用gcc,gdb就是匹配的调试器。