Difference between "char *arr" and "char arr[]"

Eyal Lebedinsky eyal at echo.canberra.edu.au
Sat Sep 22 19:30:28 AEST 1990


In article <8103 at aggie.ucdavis.edu> kuan at iris.ucdavis.edu (Frank [Who me?] Kuan) writes:
>
>In file "a.c", I declare:
>char targ[128];
>
>In file "b.c" I do:
>extern char *targ;
>
>Result: I got massive errors. When I source debugged it, it told me
>that the char pointer "targ" was 0x000000. 
>
>By chance, I tried redeclaring it as "extern char targ[]" and
>the problem was fixed.
>
>Now, I always thought that "targ[]" and "char *targ" were equivalent.
>I have several places in my program where I use those two notations
>interchangeably, and this was the first time I've ever had a problem
>with it. 
>
>Could a C wizard explain to me what I'm doing wrong and what the
>correct practice is so I don't run into these horrible bugs again?

No wizard, but here it is. The compiler will allow you to mix the array/pointer
notation and will get it right. To do this it needs to know what the reality
is. In other words, once you declare the array/pointer correctly, you cac then
access it either way. The generates assembler to access a pointer is not the
same as accessing an array. C has some 'promotion rules' which define the
behaviour of the expression array[index] and pointer[index]: the name of
an array is promoted to 'a pointer to the first element'. Anyway, the short
answer is YOU MUST DECLARE IT CORRECTLY, CANNOT MIX POINTER/ARRAY IN THE
DECLARATION.
BTW, in function arguments there is another promotion rule which allows you
to mix pointer/array here.

Any clearer now ? hope so.>
>Thanks in advance.
>
>- f


-- 
Regards
	Eyal



More information about the Comp.lang.c mailing list