Search code examples
crealloc

using realloc in c 1


I don't know what's the problem in this code-

void initialize(char ***A, int r, int c){
*A = (char **)realloc(A,sizeof(char *)*r);
}

this is the call-

char **A;
initialize(&A, 10, 10);
printf("%c",A[1][1]);

Thank you.


Solution

  • A is uninitialized, try initializing it with NULL:

    char **A = NULL;
    initialize(&A, 10, 10);
    

    realloc() will behave like malloc() in that case and will correctly realloc() in further calls. Otherwise, an uninitialized pointer will be dereferenced by realloc().

    Furthermore, realloc() *A:

    realloc(*A, sizeof(char *) * r);
    

    Otherwise, you would try to realloc the pointer to the pointer of your allocated space A, which will of course fail.