Expert C Programming

(Jeff_L) #1

file 1:


int mango[100];


file 2:


extern int *mango;


...


/ some code that references mango[i] /


Here, file 1 defines mango as an array, but file 2 declares it as a pointer. But what is wrong with this?


After all, "everybody knows" arrays and pointers are pretty much the same in C. The problem is that
"everybody" is wrong! It is like confusing integers and floats:


file 1:


int guava;


file 2:


extern float guava;


The int and float example above is an obvious and gross type mismatch; nobody would expect


this to work. So why do people think it's always OK to use pointers and arrays completely
interchangeably? The answer is that array references can always be rewritten as pointer references,
and there is a context in which pointer and array definitions are equivalent. Unfortunately, this context
involves a very common use of arrays, so people naturally generalize and assume equivalence in all
cases, including the blatantly wrong "defined as array/external declaration as pointer" above.


What's a Declaration? What's a Definition?


Before getting to the bottom of this problem, we need to refresh our memories about some essential C
terminology. Recall that objects in C must have exactly one definition, and they may have multiple
external declarations. By the way, no C++ mumbo-jumbo here—when we say "object" we mean a C
"thing" known to the linker, like a function or data item.


A definition is the special kind of declaration that creates an object; a declaration indicates a name
that allows you to refer to an object created here or elsewhere. Let's review the terminology:


definition occurs in only one
place


specifies the type of an object; reserves storage for it; is used to create
new objects

example: int my_array[100];


declaration can occur multiple
times


describes the type of an object; is used to refer to objects defined
Free download pdf