斯特托克获取分段错误读取文件

strtok getting segmentation error read file

本文关键字:错误 读取 文件 分段 获取      更新时间:2023-10-16

在 strtok 上出现分段错误,我的输入字符串lyne定义为字符数组而不是指针,但似乎不起作用。 这是在C和Linux中

    typedef struct 
    {
    int x;
    char *y;
    } child;
    typedef struct{
    child *details;
    }  parent;

        fp = fopen(filename,"r"); // read mode
        char lyne[25];
        char *item;
    fgets(lyne,25,fp);  
    parent record;
        record.details= malloc (5  * sizeof(child));    
        while (fgets(lyne,25,fp)) {
            printf("test %s n",lyne);
            item = strtok(lyne," ");    
strcpy(record.details->y,item);//seg error on this line
        }
        fclose(fp);

my file looks like this
file#1
ABC 100
BCE 200

OUTPUT:
test ABC 100
Segmentation fault

您尚未将内存分配给结构子成员"y",因为您的结构是

typedef struct 
    {
    int x;
    char *y;
    } child;

你要做的是:

record.details->y = malloc(sizeof(char)*(strlen(item) + 1));
strcpy(record.details->y,item);

必须添加 使用前parent.deatils->y = (char *) malloc(24);