Here's an example of the wierdness I'm talking about:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Test {
char *name;
int age;
} ;
void testfunc (struct Test *examp) {
if ((examp=realloc(examp,3*sizeof(*examp)))==NULL) puts ("malloc fail");
puts("HERE");
fflush(stdout);
examp[0].name=malloc(5);
strcpy(examp[0].name,"five");
examp[0].age=5;
examp[1].name=malloc(5);
strcpy(examp[1].name,"four");
examp[1].age=4;
examp[2].name=malloc(5);
strcpy(examp[2].name,"nine");
examp[2].age=9;
}
int main () {
int i=0;
struct Test *examp=malloc(sizeof(*examp));
testfunc (examp);
printf("sizeof *examp:%d sizeof examp:%d\n",sizeof(*examp),sizeof(examp));
printf("%s is %d\n", examp[0].name,examp[0].age);
for (i=0;i<3;i++) {puts("X");printf("%s is %d\n", examp[i].name,examp[i].age);}
}
Everything is fine. I am surprised that *examp is 8 bytes while examp is 4 bytes, but whatever (???). However, I am a little worried the realloc doesn't really realloc inside the function, because this causes a segfault:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Test {
char *name;
int age;
} ;
void testfunc (struct Test *examp) {
if ((examp=malloc(3*sizeof(*examp)))==NULL) puts ("malloc fail");
puts("HERE");
fflush(stdout);
examp[0].name=malloc(5);
strcpy(examp[0].name,"five");
examp[0].age=5;
examp[1].name=malloc(5);
strcpy(examp[1].name,"four");
examp[1].age=4;
examp[2].name=malloc(5);
strcpy(examp[2].name,"nine");
examp[2].age=9;
}
int main () {
int i=0;
struct Test *examp;
testfunc (examp);
printf("sizeof *examp:%d sizeof examp:%d\n",sizeof(*examp),sizeof(examp));
printf("%s is %d\n", examp[0].name,examp[0].age);
for (i=0;i<3;i++) {puts("X");printf("%s is %d\n", examp[i].name,examp[i].age);}
}
Why can't I malloc the struct array inside another function and return it?