I have the following code:
struct demo{
int *(*p)[];
};
int main() {
struct demo *demo_ptr;
int a = 1;
int b = 2;
int *arr[2];
arr[0] = &a;
arr[1] = &b;
for (int i = 0; i < 2; i ) {
printf("num in array = %d\n", *arr[i]);
}
demo_ptr->p = &arr;
for(int i = 0; i < 2; i ){
printf("num in array = %d\n", demo_ptr->(*p)[i]);
}
}
I'd like to access a
and b
by demo_ptr
. But the code failed. How to assign value to p
(a pointer to array of int pointers) declared in a struct, and how to access those ints in array through demo_ptr
?
CodePudding user response:
For starters you declared a pointer to an incomplete type
struct demo{
int *(*p)[];
};
So you can not use the sizeof
operator to determine the number of elements in the pointed array.
Secondly you defined an uninitialized pointer that has an indeterminate value.
struct demo *demo_ptr;
So again dereferencing this pointer invokes undefined behavior.
You should write for example
struct demo{
int *(*p)[2];
};
and in main
struct demo demo;
//...
demo.p = &arr;
for ( size_t i = 0; i < sizeof( *demo.p ) / sizeof( **demo.p ); i )
{
printf( "num in array = %d\n", *( *demo.p )[i]);
}
CodePudding user response:
Try: *(*demo_ptr->p)[i]
.
The problem was that sub-scripting operator []
has higher priority than dereference operator *
. This can be fixed by placing parenthesis around *demo_ptr->p
.
Other issue is that demo_ptr
points to no object. Initialize it with:
struct demo *demo_ptr = malloc(sizeof *demo_ptr);
CodePudding user response:
In the following:
struct demo{
int *(*p)[];
};
the member p
is a pointer to an incomplete array type. The array type is incomplete because no length has been specified. The array element type is int *
.
The incomplete array type is not very useful. In my opinion, if the length is not fixed, it would be better to define p
as a pointer to pointer to int
:
struct demo{
int **p;
};
Then, in main():
demo_ptr->p = arr;
/* assuming arr[0] and arr[1] are valid pointers to int: */
for(int i = 0; i < 2; i ){
printf("num in array = %d\n", *demo_ptr->p[i]);
}
(Note: *demo_ptr->p[i]
is equivalent to *((demo_ptr->p)[i])
.)
The other problem in main()
is that demo_ptr
is an uninitialized pointer, so the dereferences above result in undefined behavior. It needs to point to a struct demo
or to allocated storage with size at least sizeof (struct demo)
. For example:
struct demo *demo_ptr;
struct demo demo;
demo_ptr = &demo;