Dale said:
Mark McIntyre said:
@g44g2000cwa.googlegroups.com:
char x[4]={"my"};
Remember. sweetums, 'x' is a pointer when you declare it that way.
Actually, no, this is terribly terribly wrong. In neither declaration
is 'x' a pointer - its an array[4] of char.
You're the one who's wrong, here, fucknut -- 'x' is a character pointer
when you declare it that way. That's how C stores an array in memory;
i.e., as a pointer to a chunk of RAM.
Dale, let me offer some friendly advice.
First, don't be rude.
Second, don't be simultaneously rude and wrong.
Arrays are not pointers. Pointers are not arrays. An array is not
stored in memory as "a pointer to a chunk of RAM", it's stored in
memory as an array.
The declaration
char x[4];
declares an array object, with or without an initialization. It does
not declare a pointer object.
I think what's confused you is the fact that an array name, or any
expression of an array type, is implicitly converted to a pointer to
the array's first element in most contexts. (The exceptions are the
operand of the unary "&" or "sizeof" operator, and a string literal in
an initializer.)
Run this little program and observe the output:
int main(void)
{
char x[4]={"my"};
printf("%c\n", x);
printf("%c\n", *x);
return 0;
}
The first printf() will display garbage (because it's actually printing n
the value of a pointer) but the second will display the letter 'm'
(because it's printing the value that the pointer points to). If 'x'
were not a pointer then this wouldn't even fucking compile because '*x'
would be considered invalid indirection.
The first printf() invokes undefined behavior. The expression x,
which is of array type, is implicitly converted to a pointer value
of type char*. Passing this as an argument to printf() with a "%c"
format invokes undefined behavior. It happens to display garbage,
but since you're lying to the compiler it could do anything.
In the second printf(), the subexpression x is again converted to
a value of type char*. Dereferencing this pointer value yields the
character value 'm', so you're right about this one.
And of course you're missing the require "#include <stdio.h>, so
*any* call to printf() invokes undefined behavior. On many (most?)
implementations, it happens to work anyway, but you shouldn't count
on that.
The relationship between arrays and pointers is a common source of
confusion among C newbies. You need to read section 6, "Arrays and
Pointers", of the C FAQ (google "C FAQ" to find it). I see that this
thread is cross-posted to comp.lang.c and comp.lang.c++ (which is
rarely a good idea), but this happens to be an area where C and C++
are similar.
There's a good chance that a lot of the regulars in these newsgroups
have already killfiled you, or will do so as soon as they see your
article. You may already have permanently damaged your ability to
participate here and to benefit from the advice of experts.
Be embarrassed.