<ur**@ur8x.co m> wrote in message
news:cg******** **@news-int.gatech.edu. ..
| Ivan Vecerina <to************ ***********@vec erina.com> wrote:
| > <ur**@ur8x.co m> wrote in message
| > news:cg******** **@news-int2.gatech.edu ...
| > |
| > | Why does this declaration give undefined result:
| > |
| > | file1: extern char * p;
| > Allocates memory to store a pointer, which may later be changed
| > to refer to any memory location.
| > | file2: char p[10];
| > Allocates memory for 10 characters at a fixed address.
| > When the variable p is used, the array is implicitly
| > converted to a pointer to the first element of the array.
| > |
| > | Let's assume p has been initialized, now accessing p[i]...
|
| Yes, well if p is NULL, accessing p[i] wouldn't make sense.
| But let's say p[] has been initialized, if the array is
| implicitly converted to a point to the first element, shouldn't
| pointer arithmetic get us to p + i * sizeof(char)?
This "implicit conversion" is performed by the compiler, when
it knows that an array is being used as if it were a pointer.
But the generated code and memory layout is very different.
For the array, the assembly pseudocode for p[1] looks like:
- if p is an array:
1) load the address of p in register A
2) increment register A
3) read the byte at address A
- if p is a pointer:
1) load the address of p in register A
2) load the pointer at address A into register B
3) increment register B
4) read the byte at address B
The memory layout is what my previous comments where trying
to explain (left quoted above).
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <>
http://www.brainbench.com