我有一个名为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很陌生,不知道如何调试。

最佳答案

是的,您还需要为名称分配内存。您只为结构分配

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 );

关于c - C,获取段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29181098/

10-11 22:39
查看更多