[英]Trouble with Void * casting to int/char and replacing results
我要為我的數據結構類做一個作業,但是有點麻煩。 我有一些結構,即:
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;
}
我面臨的問題是,當我嘗試打印密鑰時,即
(((Pair*)cel->info)->key)
它給我的價值與
((TMaterie*)(Pair*)cel->info)->materie
我不知道為什么
有人可以告訴我我在做什么錯嗎?
問題在於您正在覆蓋指針值,而不是寫入其指向的緩沖區。 您正在執行以下操作:
((Pair*)cel->info)->key = malloc(...);
((Pair*)cel->info)->key = key;
在第二行中,您為指針分配了key參數中傳遞的所有內容,因此您沒有使用上面分配的內存,並且該內存已泄漏。
您可能想要的是復制key參數指向的內容,可以使用strcpy
函數。 做類似的事情:
((Pair*)cel->info)->key = malloc(...);
strcpy(((Pair*)cel->info)->key, key);
您有兩個主要問題
((Pair*)cel->info)->value = (TMaterie*)malloc(sizeof(TMaterie));
[...]
((TMaterie*)(Pair*)cel->info)->materie = value.materie;
TMaterie
成員進入Cel->info
是value
,所以
((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;
您將要覆蓋內存malloc
ated關鍵。 如果我猜想key是一個字符串,請使用strcpy
((Pair*)cel->info)->key = (char*)malloc(50*sizeof(char));
[...]
strcpy(((Pair*)cel->info)->key, key);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.