2016-01-31 20 views
0

我正在讀取具有座標,城市名稱和國家名稱的位置文件。目前我只是測試,看看我是否可以將每行的第一個元素存儲在我的數組中。休耕是我在閱讀文件的樣本:是,當我嘗試存儲在我的陣列每一行的第一個元素相同的值都存儲在每個元素使用加倍方案在C中設置數組值的正確方法?

Durban, South Africa 
29 53 S 
30 53 E 

我遇到的麻煩陣列。代碼中,我迄今:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include "kml.h" 

#define LEN 128 

struct quard_t { 
     char *city; 
     char *state; 
     char *country; 
     int longitude; 
     int latitude; 

}; 

struct data_t { 
     int nval; 
     int max; 
     struct quard_t *data; 
}; 

enum {INIT = 1, GROW = 2}; 

int main(int argc, char **argv) 
{ 
     char buf[LEN]; 
     char *str; 
     int cnt = 0; 
     FILE *in = fopen(argv[1], "r") ; 
     struct data_t *data = malloc(sizeof(struct data_t)); 
     data->nval = INIT; 
     data->max = INIT; 
     data->data = NULL; 

     while (fgets(buf, LEN, in)) { 
       if (data->nval > data->max){ 
         data->data = realloc(data->data, GROW * data->max *sizeof(struct quard_t)); 
         data->max = GROW * data->max; 
       } 
       else if (data->data == NULL) 
         data->data = malloc(INIT * sizeof(struct quard_t)); 

       str = strtok(buf, " "); 
       data->data[cnt].city = str; 
       cnt++; 
     } 

     int i = 0; 
     for (; i < cnt; i++){ 
       printf("%d: %s\n", i, data->data[i].city); 
     } 

     fclose(in); 
     return 0; 
} 

休耕是輸出我得到的數字是數組,一切的指標是什麼存儲陣列中後:

190: 30 
191: 30 
192: 30 
193: 30 
194: 30 

回答

1

當您正在分配值city

data->data[cnt].city = str; 

所有你正在做的是分配一個指針,而不是實際的數據當前存儲在str。因此,當您稍後覆蓋str時,city指向的最新值爲str。要解決此問題,當爲quard_t結構分配空間時,需要爲city分配空間。然後使用strcpy將字符串複製到此新緩衝區中。您必須對statecountry字段執行相同的操作。

此外,您的data結構不是一個真正的鏈接列表。你真的只是創建了你自己的準矢量結構。一個真正的鏈表包含數據成員和一個指向結構本身的指針。我建議你對鏈表實現做一點研究。

+0

它現在有很多意義,感謝您的幫助! –

相關問題