Re: [pointers and arrays]: The difference between an array name and a pointer
- From: "Lew Pitcher" <lpitcher@xxxxxxxxxxxx>
- Date: 2 Oct 2006 10:04:06 -0700
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
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?
No. p stores an array 6 of characters.
I know p is the name of the array that contains "Hello". Is array name
a pointer?
No, but it can often be treated /as if/ it were a pointer.
In other words, is p exactly the same as &p[0]?
It depends on the context.
sizeof(p) will return 6 (the length of the reserved space), and
sizeof (&p[0]) will return the size of a character pointer
but
*p is equal to 'H', and
*(&p[0]) is also equal to 'H'
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( ).
So you already know that p is /not/ a pointer.
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?
Not necessarily. You left out a lot of context.
Often
char *q = "Hello";
is better style than
char p[] = "Hello";
when you want the string to not be modifiable (initially).
But, because neither variable is declared as non-modifiable,
p can be overwritten with a string of 0 to 5 characters + the EOS,
and
q can be overwritten with a pointer to something (either NULL or
a real object)
HTH
- --
Lew Pitcher
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.3 (MingW32) - WinPT 0.11.12
iD8DBQFFIUZ9agVFX4UWr64RAuMJAKDjlafFWoEsc2+YyZzrTjxYEKz4GACfULBM
+TThgTgF4qKJVzH9lGcNxoQ=
=Qd3q
-----END PGP SIGNATURE-----
.
- 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: Re: to get more knowledge in 'c'
- Next by Date: Re: [pointers and arrays]: The difference between an array name and a pointer
- Previous by thread: Re: [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
|