mixing pointers and arrays
alan at allegra.UUCP
alan at allegra.UUCP
Mon Aug 1 00:25:58 AEST 1983
Consider the following fragments:
--- file 1 ---
extern char *foo;
func() {
printf("%c", *foo);
}
--- file 2 ---
char foo[SIZE];
---
The declaration
extern char *foo;
says that foo is a variable holding the address of a character (in
this case, the first character of an array). This is not correct.
The variable foo doesn't refer to a pointer to an array, but to an
array itself.
On the other hand,
main() {
char foo[SIZE];
func(foo);
}
func(foo)
char *foo;
{
printf("%c", *foo);
}
will work just fine, although it would have been clearer to declare
foo as
char foo[];
in func().
The key here is that in the first example, the foo in file one is the
same variable as the foo in file two, while in the second example, we
have two different foo's. By saying
func(foo);
we create a character pointer. In func(), foo now refers to a location
on the stack which holds the address of the first character of the array
known by the name foo in main().
Like so many other blunders, this is all done in the name of efficiency.
As far as I'm concerned, it's one of the ugliest parts of the C language.
Alan Driscoll
BTL, Murray Hill
More information about the Comp.lang.c
mailing list