c - Void * 转换为 int/char 并替换结果时出现问题

标签 c data-structures casting void-pointers

我的数据结构课有一项作业要做,我遇到了一点麻烦。我有一些结构,即:

typedef struct {
    char *materie;
    int ore_curs;
    int ore_lab;
    int credit;
    int teme;
} TMaterie;

typedef struct {
    char *nume;
    float medie;
    char grupa[6]; // 324CB + NULL
    int varsta;
} TStudent;

typedef struct {
    void *key;
    void *value;
    int frequency;
} Pair;

typedef struct celulag {
  void *info;
  struct celulag *urm;
} TCelulaG, *TLG, **ALG;

最后一个是通用列表结构,可以在信息中接受任何类型的结构。问题是我需要将它转换为结构对,以便它指向一个键(可以是 char 或 int)和一个值(可以是 TMaterie 或 TStudent 类型)。我需要制作相应分配的功能,我已经设法做到了:

TLG aloca_string_materie(char *key, TMaterie value){
    TLG cel = (TLG) malloc(sizeof(TCelulaG));
    if(!cel)
        return NULL;
    cel->info = (Pair*)malloc(sizeof(Pair));
    if( !cel->info){
        free(cel);
        return NULL;
    }
    cel->urm = NULL;
    ((Pair*)cel->info)->value = (TMaterie*)malloc(sizeof(TMaterie));
    ((Pair*)cel->info)->key = (char*)malloc(50*sizeof(char));
    ((Pair*)cel->info)->frequency = 0;
    ((Pair*)cel->info)->key = key;
    ((TMaterie*)(Pair*)cel->info)->materie = value.materie;
    ((TMaterie*)(Pair*)cel->info)->ore_curs = value.ore_curs;
    ((TMaterie*)(Pair*)cel->info)->ore_lab = value.ore_lab;
    ((TMaterie*)(Pair*)cel->info)->credit = value.credit;
    ((TMaterie*)(Pair*)cel->info)->teme = value.teme;
    return cel;
}

我面临的问题是,当我尝试打印出 key 时,即

(((Pair*)cel->info)->key)

它给了我和

一样的值(value)
((TMaterie*)(Pair*)cel->info)->materie 

我不知道为什么。

有人可以告诉我我做错了什么吗?

最佳答案

你有两个主要问题

((Pair*)cel->info)->value = (TMaterie*)malloc(sizeof(TMaterie));
[...]
((TMaterie*)(Pair*)cel->info)->materie = value.materie;

TMaterie成员进入Cel->infovalue,所以

((TMaterie*)(Pair*)cel->info)->materie

必须是

((TMaterie*)((Pair*)cel->info)->value)->materie

此外使用

((Pair*)cel->info)->key = (char*)malloc(50*sizeof(char));
[...]
((Pair*)cel->info)->key = key;

您正在为 key 覆盖 malloc 内存。 如果像我猜的那样,key 是一个字符串,只需使用 strcpy

((Pair*)cel->info)->key = (char*)malloc(50*sizeof(char));
[...]
strcpy(((Pair*)cel->info)->key, key);

关于c - Void * 转换为 int/char 并替换结果时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43231401/

相关文章:

PHP 警告 : PHP Startup: Unable to load dynamic library:/home/lib. 如此: undefined symbol :第 0 行未知中的 __gxx_personality_v0

c++ - 使用 D3D12Device 调用 DuplicateOutput 失败并出现 E_NOINTERFACE

java - 如何找到树中右 child 的高度减去左 child 的高度

c++ - 质量错误传递 sizeof casted return

c# - 从对象盒类型进行通用转换

C - 获取输入类型枚举

c - 将代码拆分为函数后,它无法正常工作。 C语言编程

data-structures - 如何将数据保存在数组中以便在 O(n) 时间内排序打印?

c++ - 打印搜索到的行

typescript - 如何在 typescript 中将枚举映射到另一个枚举?