使用C中的双指针在结构数组中进行内存分配

Bha*_*wan 4 c arrays struct pointers

下面是R使用双指针填充struct数组的示例代码.我无法分配内存r[0],并且还当函数退出,都rr[0]0x0.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct R
{
  int x;
  int y;
  char * z;
};

void func(struct R **r)
{
  r = (struct R **) malloc(4 * sizeof(struct R *));
  r[0] = (struct R *) malloc(sizeof(struct R));   // giving r[0] = 0x0
  r[0]->x = 1;
  r[0]->y = 2;
  r[0]->z = (char *) malloc(64 * sizeof(char));
  strcpy(r[0]->z , "HELLO");
}

int main()
{
  struct R *r = NULL;
  func(&r);
  printf("%d", r->x);
  printf("%d", r->y);
  printf("%s", r->z);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我无法找到背后的原因.任何帮助将受到高度赞赏.

R S*_*ahu 7

这条线

r = (struct R **) malloc(4 * sizeof(struct R *));
Run Code Online (Sandbox Code Playgroud)

更改位置r但仅在函数中本地.它不会更改调用函数中指针的值.

你需要的是:

void func(struct R **r)
{
   *r = malloc(sizeof(struct R));

   r[0]->x = 1;
   r[0]->y = 2;
   r[0]->z = malloc(64 * sizeof(char));
   strcpy(r[0]->z , "HELLO");
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是将func指针的返回值更改为使用更简单.

struct R * func()
{
   struct R *r = malloc(sizeof(*r));

   r->x = 1;
   r->y = 2;
   r->z = malloc(64 * sizeof(char));
   strcpy(r->z , "HELLO");

   return r;
}
Run Code Online (Sandbox Code Playgroud)

并在以下main用作:

struct R *r = func();
Run Code Online (Sandbox Code Playgroud)

PS请参阅我是否转换了malloc的结果?理解为什么你不应该转换返回值malloc.