ia***********@gmail.com said:
Hello all:
What's the difference between p and q in the following statements?
char p[] = "Hello";
char *q = "Hello";
p is an aggregate object, six bytes in size. sizeof p will confirm this. The
bytes contain 'H', 'e', 'l', 'l', 'o', and the null terminator character
'\0', in that order.
q is a pointer, its type being "pointer to char". Its value refers to the
place in memory where the string literal "Hello" (a six-character array
with static storage duration) is located.
I know q stores the address of 'H'.
That's a rather informal way of putting it. :-) Specifically, it stores the
address of the particular 'H' that the compiler inserts somewhere in memory
and directly follows with 'e', 'l', 'l', 'o', and the null terminator
character '\0'.
Question is: does p store the address of 'H' too?
No.
I know p is the name of the array that contains "Hello". Is array name
a pointer?
No, but it is treated like one most of the time. Exceptions: sizeof p and &p
In other words, is p exactly the same as &p[0]?
In a value context, yes. Consider that p[i] and *(p + i) mean the same
thing, recognise that & and * are complementary (and therefore cancel), and
set i to 0:
p[i] means the same as *(p + i)
&p[i] means the same as &*(p + i)
&p[i] means the same as (p + i)
&p[0] means the same as (p + 0)
&p[0] means the same as (p )
&p[0] means the same as p
p and q are the same if you want to print them out by %s.
If you mean printf will produce the same output for either when you pass
them as a match for the %s format specifier, you're right.
Is there a case where p and q (array name and pointer to the array)
can not be used interchangably? I knew there is, such as sizeof( ).
It's sizeof, not sizeof(). Yes, the other case is &
p.s. I remembered reading somewhere on the Net says that the statement
char *q = "Hello"
is not a good style of programming.
Right. Better: const char *q = "Hello";
coz you do not know whether q points to a valid address or not.
Is it true?
No, the reason is that you mustn't modify the string literal. The const
helps the compiler to remind you not to do that.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)