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 (Tom Beres) Newsgroups: net.lang.c Subject: Re: mixing pointers and arrays Message-ID: <961@rlgvax.UUCP> Date: Fri, 5-Aug-83 18:34:45 EDT Article-I.D.: rlgvax.961 Posted: Fri Aug 5 18:34:45 1983 Date-Received: Mon, 8-Aug-83 02:09:21 EDT References: <475@ihuxp.UUCP> Organization: CCI Office Systems Group, Reston, VA Lines: 53 If you realize that "char *p;" and "char p[];" are different and you don't need an explanation why, skip this. If not, read on. NEAL WYSE at ihuxp, I think you need to read this. Just because you can interchange "char *p;" and "char p[];" when declaring a formal parameter does NOT mean you can confuse these 2 everywhere else. They are NOT the same! char foo[10]; foo[1] = '\0'; means: Take the ADDRESS "foo" and add 1 to it to get a new address. Then put a '\0' in the memory location indicated by that address. char *foo; foo[1] = '\0'; means: Look at the ADDRESS "foo" and take the VALUE you find in there. Add 1 to that VALUE. Now use that VALUE as an address, and put a '\0' in the memory location indicated by that address. NOTE: I realize that "foo" should first be set to point to someplace legit. In both cases you can use indexing (i.e. "xxx[yyy]" is legit) but DIFFERENT things happen in both cases! In order for the compiler to generate the right code, it must know whether "foo" is an array or a pointer. In: file 1: | file 2: | char array[10]; | extern char *array; You are giving the wrong information to the compiler in File 2. The compiler will oblige by giving you back wrong code. You are stating in File 2 that "array" is the address of a character pointer, so the code produced will fit the 2nd description above. But File 1 says that "array" is the address of the first of 10 sequentially stored characters, so File 1 will produce code to suit the first description above. Now for the question 'why can you use "char foo[];" and "char *foo;" interchangably when declaring a formal parameter to a subroutine?'. The reason is that, as we all know, when you pass an array in C, what really gets passed to the subroutine is the address of the first element, and the parameter variable will be initialized to that address. So, the parameter is really an honest-to-goodness pointer variable. C knows that, too, and what's more is a bit lenient about it. If you declare the parameter as "char foo[];" the compiler recognizes that the whole array really won't be passed, that only the address will be, and that the parameter needs to be a pointer, so C correctly interprets the slightly misstated declaration. This leniency of interpretation is provided only when declaring parameters, nowhere else! - Tom Beres {seismo, allegra, brl-bmd, mcnc, we13}!rlgvax!tom