c - Allocating a pointer by passing it through two functions -
what doing wrong here? allocating memory original charptr or else? why can read value of charptr within func2but not in main (charptr null in main)?
#include <stdlib.h> #include <stdio.h> void func2(char *charptr) { charptr = (char *)malloc(sizeof(char)); *charptr = 'c'; printf("func2: %c\n", *charptr); } void func1(char** chardoublepointer) { //*chardoublepointer = (char *)malloc(sizeof(char)); func2(*chardoublepointer); } int main(int argsc, char* argv[]) { char * charptr = null; func1(&charptr); printf("%c\n", *charptr); }
you're missing 1 level of indirection. func2 needs ti take char** func1. when write:
void func2(char *charptr) { charptr = (char *)malloc(sizeof(char)); *charptr = 'c'; printf("func2: %c\n", *charptr); } you're assigning local variable charptr, has no effect on outside program. instead, write:
void func2(char **charptr) { *charptr = malloc(sizeof(char)); //don't cast result of malloc **charptr = 'c'; printf("func2: %c\n", **charptr); } change name chardoubleptr if insist.
and phone call in func1 like:
func2(charptr); c pointers malloc double-pointer
No comments:
Post a Comment