confusion with char *a and char a[NUM]
Doug Gwyn
gwyn at smoke.brl.mil
Tue Dec 4 01:15:27 AEST 1990
In article <7656 at umd5.umd.edu> jjk at astro.umd.edu( Jim Klavetter) writes:
> char a[NUM]
> char *a with a malloc of NUM+1 characters.
>I guess I can stop there and ask the general question, "what is the
>difference between those two?"
The first is an array of char of length NUM, and the second is a pointer
to char (which you claim has been obtained from malloc()).
>If done properly, they will both be NUM+1 bytes (or whatever a char is)
>of memory and should be accessible either by a[3] or *(a+3) for the
>forth element, for example.
Wrong -- only the array IS "NUM" (not NUM+1) bytes of storage; the
pointer is (typically) always four bytes of storage no matter what it
points to.
> strcpy(string, a)
What happens here is obvious in the case that "a" is a pointer; the
pointer is simply copied-in as an argument to the function. When "a"
is the name of an array, on the other hand, a special conversion rule
of C comes into play: In most (but not all) expression contexts, the
name of an array is replaced by a pointer to the first element of the
array. (An exception is when the array name is the operand of "sizeof".)
> a=strchr(string, ":");
> 121: incompatible types in assignment
First, you need to #include <string.h> so that strchr() gets properly
declared as returning char* (otherwise it will be assumed to return int,
which is indeed incompatible with pointer types). Assuming that a proper
declaration of strchr() is in scope, then assigning the char* return
value to a char* variable is okay, but assignment (of anything at all)
to an array is never okay.
ARRAYS ARE NOT POINTERS.
More information about the Comp.lang.c
mailing list