在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
答案 0 :(得分:0)
不得不补充一下
使用前parent.deatils->y = (char *) malloc(24);
答案 1 :(得分:0)
由于结构是
,您还没有将内存分配给struct子成员'y'typedef struct
{
int x;
char *y;
} child;
你要做的是:
record.details->y = malloc(sizeof(char)*(strlen(item) + 1));
strcpy(record.details->y,item);