2013-09-30 35 views
0

獲取strtok分段錯誤,我有我的輸入字符串lyne定義爲字符數組而不是指針,但似乎沒有工作。這是在C語言和Linuxstrtok獲取分段錯誤讀取文件

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

@jxh:你認爲'printf'調用是幹什麼的,如果不產生輸出? –

+1

[Works for me](http://ideone.com/COSpAv)。這個問題必須在其他地方,在你沒有顯示的代碼中。 –

+0

@jxh:這正是OP顯示的內容。 「文件#1」行被跳過;輸出從第二行開始。 –

回答

0

您還沒有分配的內存的struct子成員「Y」爲您的結構

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

之前添加 parent.deatils->y = (char *) malloc(24);你要做的是:

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

一直在使用它