|C Tutorial||Pointer type effects|
Advanced C Arrays
Pointer Style and strcpy()
Pointer Type Effects
Arrays and Pointers
Array Names Are Const
Advantages of being in the heap
Disadvantages of being in the heap
Both [ ] and + implicitly use the compile time type of the pointer to compute the
element_size which affects the offset arithmetic. When looking at code, it's easy to
assume that everything is in the units of bytes.
p = p + 12; // at run-time, what does this add to p? 12?
The above code does not add the number 12 to the address in p-- that would increment p
by 12 bytes. The code above increments p by 12 ints. Each int probably takes 4 bytes, so
at run time the code will effectively increment the address in p by 48. The compiler
figures all this out based on the type of the pointer.
Using casts, the following code really does just add 12 to the address in the pointer p. It works by telling the compiler that the pointer points to char instead of int. The size of char is defined to be exactly 1 byte (or whatever the smallest addressable unit is on the computer). In other words, sizeof(char) is always 1. We then cast the resulting
(char*) back to an (int*). The programmer is allowed to cast any pointer type to any other pointer type like this to change the code the compiler generates.
p = (int*) ( ((char*)p) + 12);
Want To Know more with
Contact for more learning: webmaster@freehost7com