
Question about arrays and pointers
Quote:
>As we all know, array names in C are actually pointers.
No, array names desingate arrays, just as integer variable names
designate integers structure variable names designate structures and so on.
Quote:
> So, as I understand
>it, when I declare:
>char string[10];
>what I've actually done is allocated 10 * sizeof(char) bytes on the
>application heap.
Space for 10 characters has been allocated somewhere, not necessarily on
any "heap".
Quote:
> The pointer to that allocated block is then assigned to
>string.
No, no pointer object is created. string represents the array of 10
characters, not a pointer variable.
Quote:
> Written out longhand, the following piece of code should be
>equivalent to the above declaration (except I have to free it manually):
>char *string;
>string = (char *)malloc(10 * sizeof(char));
This does create a separate pointer object so is not equivalent.
Quote:
>Moving right along then, string is a pointer. By definition, it contains an
>address and resides in a separate part of memory from the entity which it
>points to. Therefore, if I examine the value of &string, it should be
>different from the address contained IN string. This is precisely what I
>observe when I use malloc to create the array.
>On the other hand, with the simple array declaration, what I observe is that
>&string and the value contained in string are EQUAL. Therefore, string
>points to itself. I ask the following: If string points to itself, how
>can it point to the beginning of the array at the same time? The beginning
>of the array cannot occupy the same memory as string.
Since string designates the array and not a separate pointer the behaviour
you see is to be expected. Your confusion probably stems from the fact
that when the value of an array is taken in an expression it produces a
pointer to its first element. So
char *p = array;
works and initialises p with a pointer to the first element of array.
Consider
int i;
int *ip = &i;
Here i is a simply integer variable. ip is assigned a pointer to i. That
doesn't mean that the definition of i created a pointer variable in addition,
just that i has an inherent address that the & operator gives you. Similarly
you can write
char *p = &array[0];
which gives you a pointer to the first element of array. If you like you
can think of C having a shorthand way of writing this, i.e. just
char *p = array;
This gives you the inherent address of a[0] just as &i gives you the
inherent address of i. There's no need for an extra variable/object to
store this address.
--
-----------------------------------------
-----------------------------------------