Expert C Programming

(Jeff_L) #1

  1. Get the address that p represents, and retrieve the pointer there.

  2. Add the offset that the subscript represents onto the pointer value.

  3. Access the byte at the resulting address.


The compiler has been told that p is a pointer to char. (In contrast, an array definition tells the


compiler that p is a sequence of chars.) Making a reference to p[i] says "starting at where p points,


step forward over 'i' things, each of which is a char (i.e., 1 byte long)." For pointers to different types


(int or double, etc.) the scaling factor (the size of each thing stepped over) will be a different


number of bytes.


Since we declared p as a pointer, the look-up happens this way regardless of whether p was originally
defined as a pointer (in which case the right thing is happening) or an array (in which case the wrong


thing is happening). Consider the case of an external declaration extern char *p; but a


definition of char p[10];. When we retrieve the contents of p[i] using the extern, we get


characters, but we treat it as a pointer. Interpreting ASCII characters as an address is garbage, and if
you're lucky the program will coredump at that point. If you're not lucky it will corrupt something in
your address space, causing a mysterious failure at some later point in the program.


Match Your Declarations to the Definition


The problem of the external declaration of a pointer not matching the definition of an array is simple
to fix—change the declaration so it does match the definition, like this:


file 1:


int mango[100];


file 2:


extern int mango[];


...


/ some code that references mango[i] /


The array definition of mango allocates space for 100 integers. In contrast, the pointer definition:


int *raisin;


requests a place that holds a pointer. The pointer is to be known by the name raisin, and can point


to any int (or array of int) anywhere. The variable raisin itself will always be at the same address,


but its contents can change to point to many different ints at different times. Each of those different


ints can have different values. The array mango can't move around to different places. At different


times it can be filled with different values, but it always refers to the same 100 consecutive memory
locations.

Free download pdf