【问题标题】:Adding a new entry to struct array overrides all last entries向结构数组添加新条目会覆盖所有最后的条目
【发布时间】:2016-10-06 03:29:21
【问题描述】:

我正在编写一个程序,它从文件中读取信息,为每一行的结构分配内存,并用信息填充该结构。然后将指向该结构的指针放置在全局数组中。

文件中的每一行(第一行除外)的格式为“Unsigned Char - Char - Unsigned Char - Char[]”。

我的问题是每次我添加一个新结构时,所有其他结构中的 Char[] 都会被覆盖。

假设我有以下文件:

1 10 6 first
2 12 7 second
3 15 6 third

当我使用该文件运行我的程序,然后打印全局数组时,它会给出如下输出:

ID: 1 | FLAGG: 10 | STR_LEN: 6 | MODELL: third
ID: 2 | FLAGG: 12 | STR_LEN: 7 | MODELL: third
ID: 3 | FLAGG: 15 | STR_LEN: 6 | MODELL: third

而不是预期的:

ID: 1 | FLAGG: 10 | STR_LEN: 6 | MODELL: first
ID: 2 | FLAGG: 12 | STR_LEN: 7 | MODELL: second
ID: 3 | FLAGG: 15 | STR_LEN: 6 | MODELL: third

代码:

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

#define MAX_LENGTH 256

struct myStruct* globarlArray[MAX_LENGTH]

struct mySTruct{
    unsigned char ID;
    char FLAGG;
    unsigned char str_len;
    char* modell;
};

int set_variables(struct myStruct* s, unsigned char new_ID, char new_FLAGG, unsigned char new_str_len, char* new_modell){
    s->ID = new_ID;
    s->FLAGG = new_FLAGG;
    s->str_len = new_str_len;
    s->modell = new_modell;
    return 0;
}
int main(int argc, char* argv[]){
    //Read from file
    ...
    //Initialize structs, add variables to struct, and add struct to global array
    unsigned char ID;
    int ID_INT;
    char FLAGG;
    unsigned char str_len;
    char modell[253];
    char* tempstr;

    for (i = 1; i < lines; i++){
        tempstr = str[i]; //str[1] is first line of into from file, str[2] is second line,...
        Ruter_ID = tempstr[0];
        Ruter_ID_INT = Ruter_ID;
        FLAGG = tempstr[1];
        str_len = tempstr[2]; 
        sprintf(modell, "%s", tempstr+3);
        struct myStruct *line = (struct myStruct*)malloc(sizeof(struct myStruct));
        set_vars(line, ID, FLAGG, str_len, modell);
        globalArray[ID_INT] = line;
    }
    //print array
    for (i = 0; globalArray[i] != NULL; i++){
        printf("ID: %d | FLAGG: %d | str_len: %d | Modell: %s", 
        globalArray[i]->ID, globalArray[i]->FLAGG, globalArray[i]->str_len, 
        globalArray[i]->modell);
    }
    //Some more code
    ...
}

提前致谢!

【问题讨论】:

  • 请贴出可以编译的真实代码
  • 你只有一个字符缓冲区,char modell[253];。您的代码使所有s-&gt;modell 指向同一个缓冲区。
  • 指针懂吗?

标签: c arrays struct


【解决方案1】:

我的问题是每次我添加一个新结构时,所有其他结构中的 Char[] 都会被覆盖。

这是因为您正在使用:

    set_vars(line, ID, FLAGG, str_len, modell);

modell 是一个数组。您正在将指向该数组第一个元素的指针存储在 myStruct 的每个实例中。

您需要为myStruct 的每个实例分配内存并存储该指针1

    char* copy = strdup(modell);
    set_vars(line, ID, FLAGG, str_len, copy);

然后您需要确保副本已被释放。


1strdup 不是标准库函数,但可以轻松实现。

【讨论】:

    【解决方案2】:

    你的modell 数组被反复使用——你的每个结构都指向同一个内存块。你应该给你的每个结构一个字符串的副本(也许通过使用strcpy() 或相关函数。(当你释放结构时,你也必须担心释放该副本的内存)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 2021-05-01
      • 1970-01-01
      • 2015-02-08
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多