【问题标题】:Proper way to set array values in C with doubling scheme?使用加倍方案在 C 中设置数组值的正确方法?
【发布时间】: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


    【解决方案1】:

    当你给city赋值时:

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

    您所做的只是分配一个指针,而不是当前存储在str 中的实际数据。所以当你稍后覆盖str 时,city 指向的是str 的最新值。要解决此问题,您需要在为quard_t 结构分配空间时为city 分配空间。然后使用strcpy 将字符串复制到这个新缓冲区中。您必须对 statecountry 字段执行相同的操作。

    另外,您的data 结构并不是真正的链表。你真的只是创建了你自己的准向量结构。真正的链表具有数据成员和指向结构本身的指针。我建议你对链表实现做一些研究。

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多