【发布时间】:2013-09-30 02:22:36
【问题描述】:
在 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
【问题讨论】:
-
@jxh:如果没有产生输出,你认为
printf调用在做什么? -
Works for me。问题必须在其他地方,在你没有显示的代码中。
-
@jxh:这正是 OP 所显示的。跳过“file#1”行;输出从第二行开始。
-
@IgorTandetnik:我完全不清楚“file#1”是输入的一部分。既然你这么说,我会在这一点上让提问者受益。
-
strcpy的第一个参数应该指向一个足够大的有效缓冲区。record.details->y未初始化,包含垃圾,指向内存中的某个随机地址。