【发布时间】:2016-01-31 21:45:49
【问题描述】:
我正在阅读一个包含坐标、城市名称和国家名称的位置文件。目前我只是在测试我是否可以将每行的第一个元素存储在我的数组中。以下是我正在阅读的文件示例:
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
【问题讨论】:
标签: c arrays linked-list