Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

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

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("
%c
",(***p)); /*z*/
    printf("
%c
",((*(*(p+1)+1))[6]));/*f*/
    printf("
%c
",(**(p[1]+2)));/*d*/
    printf("
%c
",(**p[1]));/*r*/
    printf("
%c
",(*(p[1][2]+2)));/*b*/
} 

the second program:

#include <stdio.h>

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

    printf("
%c
",(***p)); /*z*/
    printf("
%c
",((*(*(p+1)+1))[6]));/*f*/
    printf("
%c
",(**(p[1]+2)));/*d*/
    printf("
%c
",(**p[1]));/*r*/
    printf("
%c
",(*(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',''} but I thought its the same as "xyz".

question from:https://stackoverflow.com/questions/65846563/access-via-pointer-to-2d-char-array-warning-excess-elements-in-array-initializ

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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',''} is. So the code doesn't work for the same reason as

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

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',''} but not recommended, since this compound literal will reside in different memory than the string literals.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...