Re: [pointers and arrays]: The difference between an array name and a pointer
- From: "pemo" <usenetmeister@xxxxxxxxx>
- Date: Mon, 2 Oct 2006 17:41:00 +0100
iamchiaweilin@xxxxxxxxx wrote:
Hello all:
What's the difference between p and q in the following statements?
char p[] = "Hello";
char *q = "Hello";
I know q stores the address of 'H'.
Question is: does p store the address of 'H' too?
I know p is the name of the array that contains "Hello". Is array name
a pointer?
In other words, is p exactly the same as &p[0]?
p and q are the same if you want to print them out by %s.
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( ).
One difference is that *q = ? [or q[0] = ???] may not work - as "Hello" here
may *not* be writeable [readonly] - however *p = ? and p[0] = ? will work -
it's shorthand for char p[] = { 'H', 'e', ... };, i.e., simple array
initialisation. Anyway, yes, p stores the address of *its* 'H' as does q.
p.s. I remembered reading somewhere on the Net says that the statement
char *q = "Hello"
is not a good style of programming. coz you do not know whether q
points to a valid address or not.
Is it true?
No - if the code compiles, and there isn't some catastrophic runtime error,
then q points to the address where 'H' is stored.
.
- References:
- [pointers and arrays]: The difference between an array name and a pointer
- From: iamchiaweilin
- [pointers and arrays]: The difference between an array name and a pointer
- Prev by Date: %d,%u,%c
- Next by Date: Re: %d,%u,%c
- Previous by thread: [pointers and arrays]: The difference between an array name and a pointer
- Next by thread: Re: [pointers and arrays]: The difference between an array name and a pointer
- Index(es):
Relevant Pages
|