【问题标题】:Why does the new address from realloc not get reflected outside the function?为什么来自 realloc 的新地址没有反映在函数之外?
【发布时间】:2014-10-24 05:44:16
【问题描述】:

我在这里标记了四个 printf 语句。我的问题是,在完成发生重新分配的函数 AddSub 后,应该分配给 struct sub *a 的 struct sub *temp 包含的地址在程序返回到我打印的函数 main 时不会得到反映struct sub *dstore 的地址。

第一个、第二个和第三个 printf 语句显示重新分配成功(printf 2 显示 temp 收到了新地址,print 3 显示该地址已分配给 a)。但是我很困惑为什么第四个 printf 显示不同。

struct sub {
  char code[8];
  float units;
  char tag[101];
};

void AddSub(struct sub *a, struct cla *b, int *ctr){
  char ecode[8], etags[101];
  float eunits;
  struct sub *temp = a;

  scanf("%s %f %s", ecode, &eunits, etags);

  if (!(AlIn(ecode) + UnCh(ecode, a, *ctr)))
  {
    if(*ctr)
    {
      printf("Before realloc: %p, %p\n", (void*)a, (void*)temp); /*1st*/
      temp = realloc(a, (*ctr + 1) * sizeof(*a));               
      printf("After realloc: %p, %p\n", (void*)a, (void*)temp); /*2nd*/     
    }

    if(!temp)
    {
      printf("Insufficient space.\n");
      free(a); free(b);
      exit(1);
    }
    else
    {
      if(*ctr)
      {
        a = temp;               
        printf("After AddSub readdress: %p, %p\n", (void*)a, (void*)temp); /*3rd*/
      }

      strcpy((a + *ctr) -> code, ecode);
      (a + *ctr) -> units = eunits;
      strcpy((a + *ctr) -> tag, etags); 

      printf("%s saved. ", (a + *ctr) -> code);
      *ctr = *ctr + 1;
    }
  }     
}

int main()
{
  char com[14];
  int subctr = 0, clactr = 0;
  struct sub *dstore;
  struct cla *cstore;
  if (!(dstore = malloc(sizeof(struct sub))))
    exit(1);
  if (!(cstore = malloc(sizeof(struct cla))))
  {
    free(datastore);
    exit(1);
  }

  while(1)
  {
    printf("INPUT> ");
    scanf("%s", com);

    if(strcmp(com, "ADD-SUBJECT") == 0)
    {
        AddSub(dstore, cstore, &subctr);
        printf("Finished Addsub: %p\n", dstore);  /*4th*/
    }
    else if (strcmp(com, "EXIT") == 0)
    {
        printf("Bye!\n");
        free(dstore); free(cstore); 
        return 0;
    }
    else
        printf("What?.\n");     
  }
}

【问题讨论】:

  • 因为在 C 中,函数参数是按值传递的(它们被复制)。如果你给函数内部的参数赋值,它只会影响函数本地的副本,而不影响调用者本身的原始参数。

标签: c realloc


【解决方案1】:

C 使用按值传递。例如,当您有:

void func(int a)
{
    a = 5;
}

int main()
{
    int b = 6;
    func(b);
    printf("%d\n", b);
}

输出是6。这个小例子本质上就是你的代码中发生的事情,5realloc 替换,int 被指针类型替换。

为了在函数中设置变量并使这些更改在函数外部可见,您需要通过引用传递变量,或者返回变量。

【讨论】:

  • “按引用传递”是指允许被调用函数引用调用函数中的变量的技术。 See here for details
【解决方案2】:

而不是声明

void AddSub(struct sub *a, struct cla *b, int *ctr)

使用

 a

路过

   AddSub(dstore, cstore, &subctr);

声明

   void AddSub(struct sub **a, struct cla **b, int *ctr)

使用

   *a

然后通过

  AddSub(&dstore, &cstore, &subctr);

与您对 subctr 所做的相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2021-05-13
    相关资源
    最近更新 更多