mixing pointers and arrays
tom at rlgvax.UUCP
tom at rlgvax.UUCP
Sat Jul 30 07:48:09 AEST 1983
Concerning the following:
extern char *x;
main() {
foo();
printf("%s", *x);
}
-----------------------------<new file>----------
char x[10];
sub() {
x[0] = 'a';
x[1] = '\0';
}
First, the reason the program won't work is that it should be
"printf("%s", x);" WITHOUT the indirection on x. What was originally
written passes a single character to printf() where a pointer (address)
was expected.
Second, the declaration "extern char *x;" is incorrect. "x" is an array,
NOT a pointer, and must be declared as such. The compiler thinks that
x is a pointer (i.e. a storage location containing an address). When
you pass x to printf(), x is evaulated, i.e. the contents of that location
is pushed onto the stack. However, in reality x is an ARRAY! This means
that what "the contents of that location" is in fact a bunch of characters.
So, you are passing a bunch of characters which are being interpeted as
an address. So, you blow up. Solution: in main, declare "extern char x[];".
The example you mention:
char *foo, bar[10];
foo = bar;
works because using "bar" by itself is exactly the same as "&(bar[0])"
by definition in C, not because you can treat pointers and arrays
indiscriminately. This next example also works for the same reason.
main() {
char foo[10];
subr(foo);
}
subr(bar) char *bar; {
}
I find that most new programmers find this second example confusing to say the
least.
- Tom Beres
{seismo, allegra, brl-bmd, mcnc, we13}!rlgvax!tom
More information about the Comp.lang.c
mailing list