c++ - Why to specify a pointer type? -
this question has answer here:
what happens while declaring pointer of specific type? there use specify type pointer other pointer arithmetic or indexing?
type of pointer needed in following situations
- dereferencing pointer
- pointer arithmetic
here example of dereferencing pointer.
{ char *ptr; //pointer of type char short j=256; ptr=&j; // have ignore warnings printf("%d",*ptr) } now because ptr of type char read 1 byte. binary value of 256 0000000100000000 because ptr of type char read first byte hence output 0.
note: if assign j=127 output 127 because 127 hold first byte.
now, example of pointer arithmetic:
{ int *ptr; int var=0; ptr=&var; var++; ptr++;// pointer arithmetic } are statements var++ , ptr++ same thing? no, var++ means var=var+1 , ptr++ means ptr=ptr+4. because compiler "knows" pointer , points int, adds 4 ptr instead of 1, pointer "points to" next integer.
Comments
Post a Comment