werasm wrote:
>
> > No, it is not. 'x' is not a pointer, not any kind of pointer to
> > anything.
>
> Hi Jack,
>
> According to Bjarne Stroustrup:
>
> "The name of an array can be used as a pointer to its initial element."
>
> In my own words - "The name of an array is implicitly convertable to a
> pointer pointing to the address location of its first element..."
>
> While I do understand that x is in actual fact "the name of a region
> that is large enough to store four chars" - or simply the name of an
> array of characters of for elements, my point remains that, in contrast
> to this case...
>
> char* x = new char[4];
>
> ... the type of x in case...
>
> char x[4];
>
> ...is very similar (or effectively the same as) to...
>
> char* const x = new char[4];
Well. I see where you are heading at, but yet this is not true. The type
is convertible, but that's all. So whenever the compiler has an array[] type
and there is need to convert, eg. because a function accepts a pointer, the
compiler can do this under the hood. But never say: *an array is a pointer*
or varitions of that, since it is plain wrong.
eg.
abcd.h
******
char foo[] = { "hello" }; // declare an array
defgh.cpp
*********
#include <stdio.h>
extern char* foo;
int main()
{
printf( "%s", foo );
}
this will fail without a doubt for exactly that reason: an array is not a pointer,
not even close. But: In some cicumstances an array can act 'as if it were' a pointer.
AFAIK there were 2 resons for this:
* passing arrays to functions which K&R felt to not be necessary and thereby bypassing the
problem of what to do with non matching array sizes (that especially would have been a
problem with some character arrays acting as string storage).
* Array indexing is defined in terms of pointer arithmetic.
a[i] is equivalent to *(a+i)
(a beeing an array and i beeing an index).
Especially the last point is the explanation, why one can do:
char c = malloc(4);
c[3] = '\0';
The compiler immediatly transforms this to
*(c+3)
and applies the usual pointer arithmetic.
Doing the same with an array
char d[4];
d[3] = '\0'
again: The compiler transforms this into
*(d+3) = '\0'
and now the array to pointer conversion kicks in, and converts the array
to a pointer to its first element. Then the usual array arithmetic can be done.
But even if both versions look equivalent on the C source code level (or C++), the
generated machine code is usually different.
*(c+3) is converted to ( c beeing a 'real pointer')
fetch value for c
add 3
assign '\0' to that memory address
*(d+3) translates to:
load address of d
add 3
assign '\0' to that memory address
NB: If you have sorted out this issue with a newbie

there is an easy way
to further confuse him. Introduce him to
char e[4];
3[e] = '\0';
and ask if it is valid and if yes, why?
--
Karl Heinz Buchegger