I just fail to understand the error in the following program.What I have done is I've assigned the address of an array of size 5 to a pointer ptr of type (*)[]
.There is no type mismatch and it's ok as far as that goes.But then I want to print the value ptr+1.As I expected, it shows an error about unspecified bounds.But it just misses me how the same ptr+1
works fine when I cast it to type void*
.
Casting is fine, but before it comes to that,how can the program calculate ptr+1
as it simply doesn't know the bounds? How would it know whether to move 5 elements ahead, or 8 elements ahead or any elements ahead?Why doesn't (void*)ptr+1
show the same error as ptr+1
?
To better highlight the whole thing, I have also used a pointer ctr
which is explicitly declared to be of type (*)[5]
instead of (*)[]
. Please give me the technical reasons behind this.Thank you.
#include<stdio.h>
int main(void)
{
int ar1[5]={1,5,3,8,9};
int (*ptr)[]=&ar1,(*ctr)[5]=&ar1;
printf("%p\n",ptr+1); //ERROR about unspecified bounds
printf("%p\n",(void*)ptr+1); //It's ok
printf("%p\n",ctr+1); //It's ok
}
PSST!! The last two correct printf()
s don't produce the same value.If I comment out the incorrect printf("%p\n",ptr+1);
line, this is the output.
0023FF25
0023FF38
PSST!!
I checked it again, int the ptr+1
part of (void*)ptr+1
, a 1
is simply being added to the numeric value of ptr
.What's going on?