piperRyan
piperRyan

Reputation: 507

How do I initialize a char** from a different function?

I am getting a segmentation fault on the following code:

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

void init_test(char ***test) {
    *test = malloc(2 * sizeof(char *));
    *test[0] = malloc(3); 
    *test[1] = malloc(3); 
    strcpy(*test[0], "12"); 
    strcpy(*test[1], "13"); 
}

int main()
{
    char **test = NULL;
    init_test(&test); 
    printf("1: %s, 2: %s", test[0], test[1]); 
    printf("Hello World");
    return 0;
}

I have couple of different variations of this, but I am not sure how to correctly initialize a char** in a different function.

Upvotes: 2

Views: 61

Answers (2)

dbush
dbush

Reputation: 223719

The array index operator has higher precedence than the dereference operator. You need to add parenthesis:

(*test)[0] = malloc(3); 
(*test)[1] = malloc(3); 
strcpy((*test)[0], "12"); 
strcpy((*test)[1], "13"); 

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

It's a matter of operator precedence. The expression *test[0] is equal to *(test[0]), not (*test)[0] as you seem to expect.

Upvotes: 3

Related Questions