Reputation: 16837
I want to ask what does C do when it sees an index on a pointer to pointer; for example:
struct X {
int a;
int b;
};
struct X ** ptr;
What will happen if a statement contains :
ptr[i] // where i is an unsigned int
Upvotes: 2
Views: 141
Reputation: 409404
Any pointer can be used with array indexing, so ptr[i]
will be a pointer to struct X
.
However, you have to allocate memory for ptr
first of course, otherwise you will dereference an uninitialized pointer leading to undefined behavior. And if you dereference ptr[i]
without initializing that pointer, then you're again have undefined behavior.
Upvotes: 3
Reputation: 2081
the pointer is only derefernced only once. This means the type of the expression is struct X *
.
You now have a 1D pointer array to all pointer with the a particuar row of your first 2D array.
Upvotes: 0
Reputation: 419
It returns a garbage value. Since "ptr" is a pointer to a pointer. You haven't declared what it's actually pointing to. For example..
#include<stdio.h>
struct X {
int a;
int b;
};
int main()
{
struct X ** ptr;
unsigned int i=1;
printf("%d",ptr[i]);
return 0;
}
I got the output.
1483736418
which is a garbage value of a pointer that I haven't defined.
Upvotes: 1