Pointer to char question

Hi,

I don't really understand this:

char* testvar = "Hello, world!";

Why does this work with a pointer? A char can only contain one char?
Last edited on
Why does this work with a pointer? A C string is an array of chars -so a pointer to the first character-: http://www.cplusplus.com/doc/tutorial/ntcs/
A char can only contain one char? Yes
Hi Bazzy

I understand that a C string is an array of characters, but why will this work?

cout << testvar << endl;

How does the compiler knows it should display "Hello, world!" if that pointer points to the first character?

char testvar[13] and char* testvar both seems to work, but why?
There is an operator<<( const char* ) overload for streams that assumes you meant to output
all characters up to the next null terminator. (ie, it assumes you are outputting a C-style string).
The thing is, a "pointer to some thing", is also a "pointer to an array of some things".
For example, suppose you have this:
1
2
int a=10;
int *p=&a;

It's also perfectly legal (for the compiler) to do this:
 
int b=p[10];

Because all pointers point to arrays, whenever you use *p, you can use p[0], and viceversa.
Ok, thanks =)
I'm not good at explaining so it might be wrong.

This is a pointer the to an array of chars or was it a pointer to a string
char * pword = "Hello program!";

It's the same as writing this, but this version uses the offset[] operator which deRefences the pointer
char word[20] = "Hello program";

This is why you can use the pointer like this
1
2
cout << pword[2];    // this is a legal way of accessing the value at pword[2]
                      // which is 'l'  

Because the first element is 'H' then 'e' then 'l' this is number 2.
Actually, both syntaxes are not equivalent.
The former makes a pointer that points to a char array allocated statically by the compiler. This array, like all static arrays, cannot be modified, but the pointer itself can be made to point elsewhere.
The latter makes 'word' be an alias for a a stack address that refers to an array created in the stack. Like all stack arrays, this one can be modified, but 'word' cannot be made to point elsewhere.
Last edited on
Topic archived. No new replies allowed.