| C Tutorial | Arrays and pointers | |||
|
Advanced C Arrays Plus Syntax Pointer Style and strcpy() Pointer Type Effects Arrays and Pointers Array Names Are Const Heap Memory Memory Management Dynamic Arrays Advantages of being in the heap Disadvantages of being in the heap Dynamic Strings
|
dad
One effect of the C array scheme is that the compiler does not distinguish meaningfully between arrays and pointers-- they both just look like pointers. In the following example, the value of intArray is a pointer to the first element in the array so it's an (int*). The value of the variable intPtr is also (int*) and it is set to point to a single integer i. So what's the difference between intArray and intPtr? Not much as far as the compiler is concerned. They are both just (int*) pointers, and the compiler is perfectly happy to apply the [] or + syntax to either. It's the programmer's responsibility to ensure that the elements referred to by a [] or + operation really are there. Really its' just the same old rule that C doesn't do any bounds checking. C thinks of the single integer i as just a sort of degenerate array of size 1.
{ int intArray[6]; int *intPtr; int i;
intPtr = &i;
intArray[3] = 13; // ok intPtr[0] = 12; // odd, but ok. Changes i. intPtr[3] = 13; // BAD! There is no integer reserved here! }
They are the bytes which happen to be adjacent to the memory for i. They are probably being used to store something already, such as a smashed looking smiley face. The 13 just gets blindly written over the smiley face. This error will only be apparent later when the program tries to read the smiley face data.
Want To Know more with Video ??? Contact for more learning: webmaster@freehost7com |
|