Expert C Programming

(Jeff_L) #1
Why the Confusion?

Why do people wrongly think that arrays and pointers are completely interchangeable? Because they
read the standard reference literature!


The C Programming Language, 2nd Ed, Kernighan & Ritchie, foot of page 99:


As formal parameters in a function definition


turn leaf to page 100:


char s[];


and


char *s;


are equivalent;...


Arggggghhh! Argv! Argc! What a truly unfortunate place to break the page in K&R2! It is easy to
miss that the statement of equivalence is made only for the one specific case of formal parameters in
a function definition—especially since it is emphasized that subscripted array expressions can always
be written as pointer-plus-offset expressions.


"The C Programming Language," Ritchie, Johnson, Lesk & Kernighan, The Bell System Technical
Journal, vol. 57, no. 6, July-Aug 1978, pages 1991-2019:


includes a general rule that, whenever the name of an array appears in an expression, it is converted to
a pointer to the first member of the array.


The key term "expression" is not defined in the paper.


When people learn to program, they usually start by putting all their code in one function, then
progress to several functions, and finally learn how to structure a program over several files. Thus,
they get a lot of practice seeing arrays and pointers in function arguments where they are fully
interchangeable, like this:


char my_array[10];


char * my_ptr;


...


i = strlen( my_array );


j = strlen( my_ptr );


Programmers also see a lot of statements like


printf("%s %s", my_ptr, my_array);

Free download pdf