Re: [pointers and arrays]: The difference between an array name and a pointer
- From: "Scott Fluhrer" <sfluhrer@xxxxxxxxxxxxx>
- Date: Mon, 2 Oct 2006 13:04:09 -0400
<iamchiaweilin@xxxxxxxxx> wrote in message
news:1159806072.366409.117400@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hello all:Here's a paraphrase of what this means: "Mr. Compiler Sir: Please create an
What's the difference between p and q in the following statements?
char p[] = "Hello";
array of 6 char's, which I will refer to as 'p'. Also, make its initial
contents the chars 'H', 'e', 'l', 'l', 'o', 0. Oh, and I might just write
new values in the array, if I feel like it"
char *q = "Hello";Here's a paraphrase of what this means: "Mr. Compiler Sir: Please create a
pointer to char, which I will refer to as 'q'. Also, make its initial
contents point to the first char of an unnamed array of 6 chars with the
initial contents 'H', 'e', 'l', 'l', 'o', 0. I promise not to write into
the unnamed array, but I might just point q somewhere else".
No; p is an array, not a pointer.
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 nameNo, it is not. In many contexts, an array name is automatically converted
a pointer?
into a pointer to the first element, but not all.
In other words, is p exactly the same as &p[0]?No, not exactly. For example:
sizeof(p) == 6
sizeof(&p[0]) == sizeof (char *)
Here's two others:
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( ).
p = "Bye!"; /* Error! */
q = "Bye!"; /* Works great! */
And:
p[0] = 'J'; /* Yummm! */
q[0] = 'J'; /* Undefined behavior (unless you've set q to point to a
writable char) */
Nonsense. Look at the paraphrase of the definition of q I gave above --
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?
you told the compiler to point q at a valid memory location (the first char
of the unnamed array).
.
- Follow-Ups:
- Re: [pointers and arrays]: The difference between an array name and a pointer
- From: Richard Heathfield
- Re: [pointers and arrays]: The difference between an array name and a pointer
- 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: [pointers and arrays]: The difference between an array name and a pointer
- Next by Date: Re: %d,%u,%c
- 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
|