c - For (*ptr)[], why is printf("%p",(void*)ptr+1) working but not printf("%p",ptr+1)? -
this question has answer here:
- pointer arithmetic void pointer in c 7 answers
i fail understand error in following program.what have done i've assigned address of array of size 5 pointer ptr of type (*)[].there no type mismatch , it's ok far goes.but want print value ptr+1.as expected, shows error unspecified bounds.but misses me how same ptr+1 works fine when cast type void*.
casting fine, before comes that,how can program calculate ptr+1 doesn't know bounds? how know whether move 5 elements ahead, or 8 elements ahead or elements ahead?why doesn't (void*)ptr+1 show same error ptr+1?
to better highlight whole thing, have used pointer ctr explicitly declared of type (*)[5] instead of (*)[]. please give me 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 unspecified bounds printf("%p\n",(void*)ptr+1); //it's ok printf("%p\n",ctr+1); //it's ok } psst!! last 2 correct printf()s don't produce same value.if comment out incorrect printf("%p\n",ptr+1); line, output.
0023ff25
0023ff38
psst!! checked again, int ptr+1 part of (void*)ptr+1 , 1 being added numeric value of ptr.what's going on?
please give me technical reasons behind this.
the technical reason when adding one, compiler tries jump next instance of type.
example: adding 1 int pointer increment four because int 4 bytes long , point next int.
in example, ptr never specified size. it's impossible jump next element because size of element not known. once specified size making point array of 5 elements, worked again.
when casting ptr void, became easy again go next element. compiler added 1 byte.
in run:
ptr 0023ff24
((void*)ptr) + 1 0023ff25 (the base address plus 1 byte 1 element of "void")
ctr 0023ff24 (same ptr)
ctr + 1 0023ff38 (the base address, plus 20 (5*sizeof(int)) bytes 1 element of int (*)[5])
Comments
Post a Comment