Friday 15 March 2013

c - Why does the new address from realloc not get reflected outside the function? -



c - Why does the new address from realloc not get reflected outside the function? -

i have marked here 4 printf statements. problem upon finishing function addsub reallocation takes place, address contained struct sub *temp supposedly assigned struct sub *a, not reflected when programme gets function main print address of struct sub *dstore.

the first, sec , 3rd printf statements show reallocation successful (printf 2 shows temp received new address, print 3 shows address assigned a). i'm confused on why 4th printf shows otherwise.

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) { = 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); homecoming 0; } else printf("what?.\n"); } }

c uses pass value. when have, example:

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

the output 6. little illustration happening in code, 5 replaced realloc, , int replaced pointer type.

in order set variable in function , have changes visible outside function, either need pass variable reference, or homecoming variable.

c realloc

No comments:

Post a Comment