如何将变量作为struct进行使用



i将指针变量作为struct to function 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("[*]==>%sn",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 > %sn",(item->key)->vstring);
    printf("mapval > %sn",(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,%sn",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`

您在所有调用中都完全相同的指针,并且在存储 pointer 时,所有条目都将具有相同的指针到相同的Value对象。

有两种可能的解决方案:

  1. 在每次迭代中创建一个新的Value结构(使用例如malloc(;或
  2. 复制结构而不是指针(即您将结构作为 value 而不是_pair结构中的指针(
  3. (

最新更新