数组被覆盖时遇到麻烦 [英] Having trouble with array being overwritten

查看:86
本文介绍了数组被覆盖时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将拼字游戏的词典加载到内存中,但是当我打印出词典的内容时,似乎已经用buf看到的最后一个字符串重写了数据数组中的每个字符串,例如,当我在最后打印出数据数组,该数组中的每个条目都是'zzz',因为它是scrabble.txt中的最后一个条目。我不明白为什么要覆盖它?我在做什么错了?

I'm trying to load a scrabble dictionary to memory, but when I print out the contents of the dictionary, it seems to have rewritten every string in my data array with the last string seen by the buf, for example, when I print out the data array at the very end, every entry in the array is 'zzz' because its the last entry in scrabble.txt. I don't understand why it is being overwritten? What am I doing wrong?

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

#define LEN 100

struct data_t {
    int nval;       /* current number of values in array */
    int max;        /* allocated number of values */
    char **data;        /* the data array */
};

enum {INIT = 1, GROW = 2};

int main(void)
{
    FILE *fp = fopen("scrabble.txt", "r");
    char buf[LEN];
    int i = 0;
    struct data_t *data = malloc(sizeof(struct data_t));
    data->nval = INIT;
    data->max = INIT;
    data->data = NULL;
    while (fgets(buf, LEN, fp)) {
            if (data->data == NULL) {
                    data->data = malloc(LEN);
                    assert(data->data);
            }
            else if (data->nval > data->max) {
                    data->data = realloc(data->data, GROW * data->max * LEN);
                    assert(data->data);
                    data->max = GROW * data->max;
            }
            //printf("%s\n",buf);
            data->data[i] = buf;
            //printf("data->data[%d] = %s ", i, data->data[i]);
            i++;
            data->nval++;
    }
    /* overcounted */
    data->nval--;

    for(i = 0; i < data->nval; i++)
            printf("data->data[%d] = %s", i, data->data[i]);

    fclose(fp);
    free(data->data);
    return 0;
}


推荐答案

您编写:

data->data[i] = buf;

这使指针 data-> data [i] 指向缓冲区 buf 。您每次在循环中都要执行此操作,因此最终所有指针都指向 buf 。因此,当您输出每个指针指向的内容时,它会输出 buf 的内容多次。

This makes the pointer data->data[i] point at the buffer buf. You do this every time around the loop, so you end up with all of your pointers pointing to buf. So when you output what each pointer is pointing to, it outputs the contents of buf that many times.

您可能想为每行使用不同的缓冲区。您将必须使用 malloc 或相关的来分配这些缓冲区。例如,将 data-> data [i] = buf; 替换为:

You probably wanted to use a different buffer for each line. You will have to use malloc or related to allocate those buffers. For example, replace data->data[i] = buf; with:

data->data[i] = strdup(buf);

strdup 不是标准C函数,但是如果您的系统没有它,可以先 malloc(strlen(buf)+1),然后再 strcpy )。

(strdup is not a Standard C function, but if your system doesn't have it, you can malloc(strlen(buf)+1) followed by strcpy).

这篇关于数组被覆盖时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆