如何使用C将变量作为结构传递给函数?

如何使用C将变量作为结构传递给函数?,c,dictionary,struct,C,Dictionary,Struct,我将指针变量作为结构传递给函数Put() 主要条款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

我将指针变量作为结构传递给函数
Put()

主要条款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);
}
输出:

[*]==>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`
您正在所有调用中传递完全相同的指针,并且在存储指针时,所有条目都将具有指向非常相同的
对象的相同指针

有两种可能的解决方案:

  • 在每次迭代中创建一个新的
    结构(例如使用
    malloc
    );或
  • 复制结构而不是指针(即,您将结构作为值,而不是
    \u对中的指针
    结构)

  • 把问题放在一边,在
    Put(map,&str,str.vstring)中
    您不认为
    str.vstring
    是一个冗余参数吗。当您已经通过
    &str
    时,看起来您可能已经用最终的解决方案编辑了问题。如果你已经这样做了,请回到问题的最后一个良好状态,并在下面的答案中给出解决方案。我们不会在这里用答案覆盖问题,因为这样会产生一个没有问题的答案,这对未来的读者来说是没有用处的。谢谢坦克你,修好了比如:
    Put(map,&str,str.vstring); ===>this may have problem.`&str`