Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation in array of structure using double pointers in C

Below is the sample code for populating the array of struct R using double pointers. I am unable to allocate memory to r[0] and also when the function exits, both r and r[0] becomes 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;
}

I am unable to find the reason behind it. Any help would be highly appreciated.

like image 749
Bhawan Avatar asked Dec 14 '22 17:12

Bhawan


1 Answers

The line

r = (struct R **) malloc(4 * sizeof(struct R *));

changes where r points but only locally in the function. It does not change the value of the pointer in the calling function.

What you need is:

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");
}

Another option is to change the return value of func to a pointer and make it simpler to use.

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;
}

and use it in main as:

struct R *r = func();

PS See Do I cast the result of malloc? to understand why you should not cast the return value of malloc.

like image 153
R Sahu Avatar answered May 25 '23 20:05

R Sahu