tags:

views:

151

answers:

5
char *sample = "String Value";

&sample is a pointer to the pointer of "String Value"

is the above statement right?

If the above statement right, what is the equivalent of &sample if my declaration is

char sample[] = "String Value"
A: 

The above statement is correct.

Daniel Goldberg
This is the kind of thing you should add as a comment, not an answer (I'm not one of those who downvoted you, though).
caf
...particularly so when you consider that all the answers get reordered when the votes change (or one is edited).
T.E.D.
A: 

&sample is the address of the pointer that points to "String Value".

For the second example, since an array name that is not followed by a subscript is interpreted as the pointer to the initial element of the array, which means

sample

and

&sample[0]

are the same, therefore &sample is also the address of the pointer that points to the string.

Khnle
This is not true. ` it is the address of an array, which is in no way interchangeable with the address of a pointer.
caf
jamesdlin
+5  A: 

In the first one, there are two objects being created.

One is a char * (pointer-to-char) called sample, and the other is an unnamed array of 13 chars containing the characters of the string. In this case, &sample gives the address of the object sample, which is the address of a pointer-to-char - so, a pointer-to-pointer-to-char.

In the second example, there's only one object being created; an array of 13 chars called sample, initialised with the characters of the string. In this case, &sample gives the address of the object sample - so, a pointer-to-array-of-13-chars.

In the second example, there is no "equivalent" to &sample in the first example, in the sense of a pointer-to-pointer-to-char value. This is because there is no pointer-to-char value to take the address of. There is only the array.

caf
Thank you caf.You really deserved that 25k reputation!
din
A: 

In C arrays and pointers are more or less interchangable. You can treat an array name like it is a pointer, and a pointer like it is an array name.

If you take the address of (&) of a pointer, of course you get a pointer to a pointer.

T.E.D.
caf
"more or less interchangeable" does not actually clarify anything for a beginner. (1) "The same thing," is not equivalent to "sometimes a variable declared as an array decays to a pointer to the start of the array," and (2) you'd do better to list the situations when that happens.
detly
A: 

While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precaustions using pointers to prevent errors. We should make sure that we know where each pointer is pointing in a program. Here are some general observations and common errors that might be useful to remember. *ptr++, *p[],(ptr).member

bachchan