我将指针变量作为结构体传递给函数 Put()
。
main.c:
...
enum VTYPE {VSTRING};
typedef enum VTYPE vtype;
typedef struct Value Value;
struct Value {
vtype typ;
int64_t size;
union {
char *vstring;
};
};
...
void Put(_map * map, struct Value *key, void * value){
_pair * pair = malloc(sizeof(_pair));
printf("[*]==>%s\n",key->vstring);
/*
struct Value *vkey;
vkey.vstring=malloc(key->size +1);
//vkey->vstring=malloc(key->size +1);
//vkey->vstring=key->vstring;
//pair->key = vkey;
*/
pair->key = key;
pair->value = value;
pair->next = map->items;
map->items = pair;
map->size++;
}
...
struct Value** Keys(_map*map){
int i = 0;
struct Value** keys = malloc(map->size * 10);
_pair * item = map->items;
while( item ){
printf("mapkey > %s\n",(item->key)->vstring);
printf("mapval > %s\n",(item->value));
keys[i++] = (item->key);
item = item->next;
}
return keys;
}
...
int main(int argc, char* argv[])
{
Value current;
Value str;
_map * map = newMap();
for (current.vint=1; current.vint<=5;current.vint++)
{
str.vstring=malloc(strlen("Item")+current.vint+1+1);
sprintf(str.vstring,"Item%d",current.vint);
//Put(map,str,str.vstring);
Put(map,&str,str.vstring); ===>this may have problem.`&str`
}
Value** keys = Keys(map);
for (int i = 0; i < map->size; i++)
printf(" > %d===>%d,%s\n",i,keys[i]->typ,keys[i]->vstring);
printf("\nSize:%d",map->size);
}
main.h:
...
typedef struct _pair{
struct Value *key;
void* value;
int nvalue;
struct _pair * next;
} _pair;
...
void mapPut(_map*,struct Value*,void*);
...
struct Value** mapKeys(_map*);
...
输出:
[*]==>Item1
[*]==>Item2
[*]==>Item3
[*]==>Item4
[*]==>Item5
mapkey > Item5
mapval > Item5
mapkey > Item5
mapval > Item4
mapkey > Item5
mapval > Item3
mapkey > Item5
mapval > Item2
mapkey > Item5
mapval > Item1
> 0===>0,Item5
> 1===>0,Item5
> 2===>0,Item5
> 3===>0,Item5
> 4===>0,Item5
为什么所有mapkey
都是Item5
?
因为在 for() 循环中,str 变量每次都会改变。
但在 mapkey
中都是相同的。
我尝试在没有指针的情况下将变量传递给 Put()
,但是错误!
我该如何解决这个问题?
最佳答案
你是对的。当你这样做时
Put(map,&str,str.vstring); ===>this may have problem.`&str`
您在所有调用中传递完全相同的指针,并且当您存储指针时,所有条目都将具有指向相同Value
对象的相同指针。
有两种可能的解决方案:
- 在每次迭代中创建一个新的
Value
结构(例如使用malloc
);或者 - 复制结构而不是指针(即您将结构作为值,而不是
_pair
结构中的指针)
关于c - 如何使用 C 将变量作为结构体传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43558642/