Home > Net >  Why do I get segmentation fault when I compile and run this code?
Why do I get segmentation fault when I compile and run this code?

Time:07-02

I am trying to create a char pointer array,or another way to put it a string array; using this syntax:

#include <stdio.h>

int main() {
    char **a = {"ab", "ac"};
    printf("%c", *((*a) sizeof(char)));
}

To my understanding, a is a pointer that points to a char*. When I dereference it, I must access to the char* which in this context is the pointer that points to the first char of the string literal "ab". Adding one byte to the pointer must yield the pointer, address that points to the second char to the string literal, and when dereferenced, it must yield the char: 'b'? So why does this chunk of code generate such error? Is it because the compiler doesn't allocate adequate amount of memory because I am m erely declaring a pointer instead of an array? The prior questions are just speculations and are optional for one to answer. Thanks in advance.

CodePudding user response:

char** is not an array and cannot be used as one. Except for the scenario when it points at the first item in an array of char*.

char **a = {"ab", "ac"}; is not valid C, as the compiler told you with warnings. You might want to consider a different configuration so that you won't have to waste time on things like this, see What compiler options are recommended for beginners learning C?

You could however turn this incorrect line into a valid one by having the char** point at the first item of an array. This can be done with the aid of a compound literal:

char **a = (char*[]){"ab", "ac"};

Please note however that the string literals in this code are read-only, so correct code should actually be:

const char **a = (const char*[]){"ab", "ac"};

Though maybe just drop the pointer to pointer entirely since it fills no obvious purpose here and go with a plain array instead:

const char* a[] = {"ab", "ac"};

CodePudding user response:

This declaration

char **a = {"ab", "ac"};

is incorrect. You may not initialize a scalar object with a braced list that contains more than one initializing expression.

Instead you could declare an array like

char * a[] = {"ab", "ac"};

And if you want to output the second character of the first string literal used as an initializer then you can write for example

printf( "%c", *( *a   1 ) );

Or you could declare an intermediate pointer like

char * a[] = {"ab", "ac"};
char **p = a;

and then

printf( "%c", *( *p   1 ) );

If you want to output the whole array using pointers then the corresponding program can look like

#include <stdio.h>

int main( void )
{
    char * a[] = {"ab", "ac"};

    for ( char **p = a; p != a   sizeof( a ) / sizeof( *a );   p )
    {
        for ( char *q = *p; *q;   q )
        {
            printf( "%c", *q );
        }
        putchar( '\n' );
    }
}

The program output is

ab
ac
  • Related