Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1a 7/7/83; site rlgvax.UUCP Path: utzoo!linus!philabs!seismo!rlgvax!tom From: tom@rlgvax.UUCP Newsgroups: net.lang.c Subject: Re: mixing pointers and arrays Message-ID: <919@rlgvax.UUCP> Date: Fri, 29-Jul-83 17:48:09 EDT Article-I.D.: rlgvax.919 Posted: Fri Jul 29 17:48:09 1983 Date-Received: Mon, 1-Aug-83 10:46:27 EDT References: <2332@csu-cs.UUCP> Organization: CCI Office Systems Group, Reston, VA Lines: 49 Concerning the following: extern char *x; main() { foo(); printf("%s", *x); } --------------------------------------- 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