I want to assign the address of an array of pointers to a pointer to an array of pointers. So that's what I did below for the argument of a function. It did not function correctly, it was dereferencing to incorrect values. I narrowed down the problem to the code below. But I don't understand the problem.
#include <stdio.h>
void test( char * arg[]){
char * local[] = {"break", "the", "silence", NULL};
char * (*argptr)[];
char * (*localptr)[];
argptr = &arg;
localptr = &local;
printf("address of arg %p\n", &arg);
printf("address argptr is pointing to %p\n", argptr);
printf("address of local %p\n", &local);
printf("address localptr is pointing to %p\n", localptr);
printf("arg %p\n", arg);
printf("argptr is pointing to %p\n", *argptr);
printf("local %p\n", local);
printf("localptr is pointing to %p\n", *localptr);
}
int main()
{
char * somecmd[] = {"words", "like", "violence", NULL};
test(somecmd);
return 0;
}
Output for above code:
address of arg 0x7ffd0ab3c418
address argptr is pointing to 0x7ffd0ab3c418
address of local 0x7ffd0ab3c420
address localptr is pointing to 0x7ffd0ab3c420
arg 0x7ffd0ab3c450
argptr is pointing to 0x7ffd0ab3c418
local 0x7ffd0ab3c420
localptr is pointing to 0x7ffd0ab3c420
The address of arg and the value of argptr are the same. This is also true for the address of local and the value of localptr. However, the value of arg and the value of argptr dereferenced are different. This is now what I was expecting. I expected something more like the value of local and the value of localptr dereferenced, they are the same.
Why do arg and argptr dereferenced have different values?
转载于:https://stackoverflow.com/questions/53058636/pointer-to-array-of-pointers-argument-vs-local
The below statement is an incompatible assignment.
argptr = &arg;
You would notice something like this it you have all warnings turned on:
error: assignment from incompatible pointer type [-Wincompatible-pointer-types]
argptr = &arg;
This is because of what is known as array decaying into a pointer when passed as an argument which happens in the statement test(somecmd);
So in the test
function you have to change
char * (*argptr)[];
to
char ***argptr;
Then the output will be as expected:
address of arg 000000000061FE10
address argptr is pointing to 000000000061FE10
address of local 000000000061FDD0
address localptr is pointing to 000000000061FDD0
arg 000000000061FE30
argptr is pointing to 000000000061FE30
local 000000000061FDD0
localptr is pointing to 000000000061FDD0
You will find another warning like this
warning: format '%p' expects argument of type 'void *', but argument 2 has type 'char * (*)[4]' [-Wformat=]
This is because the converstion specifier %p
expects a void*
. So in all your printf statements, do a cast to void*
like this:
printf("address of arg %p\n", (void*)&arg);