2016-03-05 35 views
-2

我有一個結構,並在一個結構我有一個字符指針,但是,我創建此結構的不同實例,但是當我更改指針在一個結構中另一個也在改變。如何讓結構指向不同的字符串?

#include <stdio.h> 
#include <stdlib.h> 

typedef struct human{ 
    int age; 
    char name[100]; 
} Human; 

int main(){ 
    FILE *s = fopen("h.txt","r"); 
    if(s==NULL){ 
     printf("file not available"); 
    } 

    for(int i=0 ;i<5;i++){ 
     Human h; 

     fscanf(s,"%d",&h.age); 
     fscanf(s,"%s",h.name); 

     insertintolinkedlist(h); 
     // this method is going to insert the human into the linked list 
    } 

    return 0; 
} 

發生了什麼事情,鏈接列表中的所有人都有不同的年齡,但同名!

+4

h.name沒有分配給它的內存。根據提供的示例代碼,我期望第二個fscanf會崩潰。 – rrrzx

+0

@rrrzx爲什麼會崩潰? –

回答

1

您需要分配內存來保存名稱。

char* name只是一個指針 - 它沒有保存名稱的內存。

將其更改爲

char name[100]; 

記住要檢查你投入Human.name名稱不超過100個字符。

使用鏈接的列表,你可以這樣做:

typedef struct human{ 
    int age; 
    char name[100]; 
    struct human* next; 
} Human; 

int main() 
{ 
    Human* head = NULL; 
    Human* tail = NULL; 

    for(.....) 
    { 
     Human* h = malloc(sizeof(Human)); 
     if (head == NULL) head = h; 
     if (tail != NULL) 
     { 
      tail->next = h; 
     } 
     tail = h; 
     h->next = NULL; 
     h->age = ....; 
     strncpy(h->age, "..name..", 100); 
    } 

    // ..... other code 

    // Remember to free all allocated memory 
} 
+0

謝謝你是對的,但即使我這樣做指針仍然指向相同的內存位置 –

+0

我總是做一個人,然後將其添加到鏈表,但這個人將有diiffernernt年齡但同名 –

+0

@ SaraHamad - 你沒有任何鏈接列表! – 4386427