0

在 strtok 上出现分段错误,我将输入字符串lyne定义为 char 数组而不是指针,但似乎不起作用。这是在 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
4

2 回答 2

0

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

于 2013-09-30T03:06:01.247 回答
0

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

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

你要做的是:

record.details->y = malloc(sizeof(char)*(strlen(item) + 1));
strcpy(record.details->y,item);
于 2013-09-30T05:01:56.190 回答