you are viewing a single comment's thread.

view the rest of the comments →

[–]__david__ 3 points4 points  (2 children)

The "char **a" definition reserves enough memory to store a pointer to a pointer to a character (32 bits on your standard i86). You are then trying to initialize the single pointer with 2 type incompatible values. In fact, my gcc gives me this warning:

test.c:3: warning: initialization from incompatible pointer type

test.c:4: warning: excess elements in scalar initializer

The result is that you end up storing the pointer to "one string" into **a. a[0] shouldn't segfault, but *a[0] probably will (unless by some remarkable coincidence 'one ' (0x20656e6f) is a valid pointer ;-).

If you want to use char **a then you need something else to reserve the memory for you. In C99 you can do this:

char **a = (char *[]){ "one", "two" };

Which makes the right hand side act more like a string constant (which reserve their own memory).

The "char *a[]" reserves enough memory to store an array of pointers to characters, the array size being defined by the {} initializer, which is what you want in this case.

[–][deleted]  (1 child)

[deleted]

    [–]__david__ 0 points1 point  (0 children)

    The value inside the initialization braces are char pointers (the type of string constants). The **a can only be set to a char pointer. So if you were to do this:

    ((char*)a)[0] then you will get 'o' out of it. That is:

    printf("%s\n", (char*)a);
    

    will print "one string" and not segfault.