Those programmers I wrote about in last week’s Lesson, the ones who avoid the **
pointer notation, usually do so by using a two-dimensional array instead of the **
pointer thing. It’s a quick substitute, but it’s not exactly the same thing.
As an example, here’s the code from Part II in this series:
#include <stdio.h> void fourchar(char **p) { int x; for(x=0;x<4;x++) { putchar(**p); (*p)++; } } int main() { char *text = "ABCD\n"; fourchar(&text); putchar(*text); return(0); }
If you just want to display four characters in a string, you could re-write the code like this:
#include <stdio.h> void fourchar(char p[]) { int x; for(x=0;x<4;x++) { putchar(p[x]); } } int main() { char text[] = "ABCD\n"; fourchar(text); return(0); }
Suppose, however, that text
were a two-dimensional array. For example, it’s declared as:
char text[2][5] = { "ABCD", "WXYZ" };
You need to pass text[0]
, which is the string "ABCD"
, to the function fourchar(). Here’s the code that does that:
#include <stdio.h> void fourchar(char p[]) { puts(p); } int main() { char text[2][5] = { "ABCD", "WXYZ" }; fourchar(text[0]); return(0); }
The argument for fourchar() is in the form array[n]
where n is an element number. The element number is omitted in fourchar()‘s declaration. And in the function itself, the variable name p
is used, but not the square brackets. This approach has some quirks, but my guess is that most pointer-fearful programmers prefer it for sending a string to a function.
But.
Suppose the purpose of the fourchar() function is to process the two-dimensional array one element at a time? In that setup, you’d still use this statement to pass the string to the function:
fourchar(text[0]);
The variable text[0]
is equivalent to the first character in the string, text[0][0]
. So far, so good. The trouble lies in the fourchar() function. You cannot do this declaration:
void fourchar(char p[][]);
The compiler has no clue what a p[][]
is. Most programmers would edit the declaration back to:
void fourchar(char p[]);
Within the function you could try using the p[][]
variable, but again the compiler would balk. In fact, you can’t even use p[]
within the function: Only variable p
represents the string passed to the fourchar() function; variable p[]
is unknown.
The best way to process a string character-by-character in this manner is to use the **
type of pointer, which is quite similar to what the text[][]
notation represents.
I’ll show that solution in next week’s Lesson.