Two-dimensional array secondary pointer parameter passing

Pointer array parameter passing

Two-dimensional arrays cannot be passed as secondary pointer parameters and cannot be cast. Right now:

void fun(char **p);
char str[2][6] = {
    
    "hello", "world"};

fun(str);

Such a call will error out.

But pointers can be converted to secondary pointers. like:

void fun(char **p);
char *str[6] = {
    
    "hello", "world"};

fun(str);

This call is OK.

Array pointer parameter passing

In the following case, the call will fail.

void func(int **p);
int ary[2][6];

func(ary);

In this case, the two-dimensional array cannot be converted into a two-dimensional pointer. Make the following modifications.

void func(int (*p)[6]);
int ary[2][6];

func(ary);

This call is correct.

As can be seen from the above example, a two-dimensional array can be converted into an array pointer, and an array of pointers can be converted into a secondary pointer. The name of a two-dimensional array is actually an array pointer, pointing to an array, so a two-dimensional array can be converted into an array pointer. An array of pointers is an array. The type of the array elements is a pointer, one is a pointer, and it has always been an array. Because the basic data type is not an array pointer, it cannot be converted. The second-level pointer is a pointer to a pointer. The name of an array pointer is a pointer, which points to an array element, and an array element is also a pointer. Therefore, an array pointer is a pointer to a pointer, so it can be converted with a second-level pointer.

The above conversion is for the default conversion.

The relationship between array pointers and pointer arrays should be as follows:

int ary[2][6];
int (*ary1)[6];
int *ary2[2];

Guess you like

Origin blog.csdn.net/duapple/article/details/108193065