Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code in C

#include <stdio.h>
 
char *gstr[] = { "Hello", "World" };
 
void func(char str[][8]) {
    printf("%p
", (void *)str);
    printf("%p
", (void *)(str + 1));
    printf("%s
", *(str + 1));
}
 
int main(void) {
    printf("%p
", (void *)gstr);
    printf("%p
", (void *)(gstr + 1));
    printf("%s
", *(gstr + 1));
 
    printf("Calling Function
");
 
    func(gstr);
    return 0;
}

The following is the output

0x556f11ddd010
0x556f11ddd018
World
Calling Function
0x556f11ddd010
0x556f11ddd018
$??oU

I cannot understand why printf("%s ", *(str+1)); in the function func does not print the string world.

question from:https://stackoverflow.com/questions/65643844/passing-array-of-pointers-to-a-function-accepting-2d-array

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

1 Answer

char *gstr[] = {"Hello", "World"}; declares gstr to be an array of pointers to char.

By itself, char str[][8] declares str to be an array of arrays of eight char. However, as a function parameter, it is automatically adjusted from an array to a pointer: It declares str to be a pointer to an array of eight char.

A pointer to an array is different from an array of pointers.

Your compiler should have warned you that the type of gstr in func(gstr) is incompatible with the type of the parameter in void func(char str[][8]). Pay attention to the messages from your compiler.

To pass gstr to func correctly, change the declaration of func to func(char *str[]) or the equivalent func(char **str).

func(gstr) passes the address of the first element of gstr to the function. Since gstr is an array of pointers, the address of its first element is the address of a pointer (that being a pointer to the first character of "Hello").

In func, the function expects a pointer to an array of eight char. If it uses the address it is given for that, it is pointing to a pointer instead of an array of eight char. Passing that to printf attempts to print the bytes representing the pointer as if they were a string of characters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...