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.