access via pointer to 2D char array. warning: excess elements in array initializer

Viewed 37

I wrote two program that I thought were the same but apparently they are not and I cant figure out why.

the first program(works as expected):

#include <stdio.h>

void main()
{
    char *p[2][3]={"xyz","wvu","ts","rqponm","lkgihgfe","dcba"}; 

    printf("\n%c\n",(***p)); /*z*/
    printf("\n%c\n",((*(*(p+1)+1))[6]));/*f*/
    printf("\n%c\n",(**(p[1]+2)));/*d*/
    printf("\n%c\n",(**p[1]));/*r*/
    printf("\n%c\n",(*(p[1][2]+2)));/*b*/
} 

the second program:

#include <stdio.h>

void main()
{
    char *p[2][3]={{'x','y','z','\0'},"wvu","ts","rqponm","lkgihgfe","dcba"}; 

    printf("\n%c\n",(***p)); /*z*/
    printf("\n%c\n",((*(*(p+1)+1))[6]));/*f*/
    printf("\n%c\n",(**(p[1]+2)));/*d*/
    printf("\n%c\n",(**p[1]));/*r*/
    printf("\n%c\n",(*(p[1][2]+2)));/*b*/
}

when I Compile this program I get a warning: excess elements in array initializer. when I run it I get an error: Segmentation fault (core dumped).

obviously the problem is in {'x','y','z','\0'} but I thought its the same as "xyz".

2 Answers

char *p[2][3] is an array of arrays of char*. Each such char* can be initialized with a string literal. You can however not initialize a char* with an array initializer syntax, which is what {'x','y','z','\0'} is. So the code doesn't work for the same reason as

char* str = {'x','y','z','\0'};

doesn't work. You get "excess element" because a pointer can only be initialized with one single initializer, not 4 as in this case.

It would be possible to initialize it with a compound literal (char[]){'x','y','z','\0'} but not recommended, since this compound literal will reside in different memory than the string literals.

You have much more warnings there.

In your code you are assigning array elements (and thet are of type pointer to char) with the char values converted to the pointer.

You need to use compound literal for that:

int main(void)
{
    char *p[2][3]={(char[]){'x','y','z','\0'},"wvu","ts","rqponm","lkgihgfe","dcba"}; 

    printf("\n%c\n",(***p)); /*z*/
    printf("\n%c\n",((*(*(p+1)+1))[6]));/*f*/
    printf("\n%c\n",(**(p[1]+2)));/*d*/
    printf("\n%c\n",(**p[1]));/*r*/
    printf("\n%c\n",(*(p[1][2]+2)));/*b*/
}

https://godbolt.org/z/5ofj6q

Related