Search code examples
carrayspointerssegmentation-faultpointer-to-pointer

Pointer-to-pointer arithmetic not behaving as expected


I have the code below and can't understand why it is segfaulting. Where am I messing up here. I am trying to learn how to access/modify a char **. Thanks!

#include <stdio.h>
#include <stdlib.h>

int main() {
    char * wordPtr;
    char **wordPtrPtr = &wordPtr;
    *wordPtrPtr = (char *) malloc(3 * sizeof(char));

    *wordPtrPtr[0] = 'A';
    *wordPtrPtr[1] = 'B';
    *wordPtrPtr[2] = '\0';

    printf("%s\n", *wordPtrPtr);

    return 0;
}

Solution

  • Watch out for operator precedence. You need to dereference wordPtrPtr first before accessing array elements:

    (*wordPtrPtr)[0] = 'A';
    (*wordPtrPtr)[1] = 'B';
    (*wordPtrPtr)[2] = '\0';