J.Doe
J.Doe

Reputation: 21

Passing a double pointers to a function to get a string in C

This is my code:

I'm a trying to pass a string through a void function with a double pointer.

void modify(char** double_pointer) {
    //define a char pointer 
    char* pointer = malloc(5*sizeof(char));
    strcpy(pointer, "test");
    printf("%s\n", pointer);                       //prints test

    // point double_pointer to pointer
    double_pointer = malloc(sizeof(char*));
    *double_pointer = pointer;
    printf("%s\n", *double_pointer);              //prints test
}

int main() {
    //pointer to a pointer
    char* double_pointer = NULL;
    modify(&double_pointer);
    printf("%s\n", *double_pointer);              // seg. fault
}

Why does printing *double_pointer in main result in a segmentation fault?

Thanks for your answers.

Upvotes: 0

Views: 1702

Answers (1)

John Kugelman
John Kugelman

Reputation: 361635

%s expects a char *. Don't dereference the pointer in main(). There it's not a double pointer, it's already the correct type. You're better off renaming it to pointer so you don't confuse yourself.

int main() {
    char* pointer = NULL;
    modify(&pointer);
    printf("%s\n", pointer);
}

Also, in modify() you should not be allocating memory for double_pointer.

// point double_pointer to pointer
double_pointer = malloc(sizeof(char*));
*double_pointer = pointer;
printf("%s\n", *double_pointer);              //prints test

Upvotes: 3

Related Questions