pas_owd
pas_owd

Reputation: 11

Where does this char* variable point?

I would like to know what s and *s mean? Where does s point?

char *s = "my name"
cout<<*s<<endl;
cout << s << endl;
cout << &s << endl;
cout << s+1 << endl;
cout << &(s+1) <<endl;   //error code

My output:

M
My name
0x61fe18
y name

Upvotes: 0

Views: 90

Answers (1)

BiOS
BiOS

Reputation: 2304

A conforming compiler may show you a similar warning:

warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings]

This is because in standard C++ if you want to initialise a char* with a string literal you need to have it const, as quoted strings in C++ are a set of const chars.

const char* s = "my name"; declares a pointer to the constant null terminated string "my name". The pointer will refer to the first element (const char), but if you try to print s as such:

cout << s << endl;

Remember: s is a pointer to a null terminated string.

Every succeeding const char will be printed until the null terminator \0 is found.

However, as s points to the first of these const char, if you try to "forcibly" print value-at-address of s, with:

cout << *s << endl;

The first letter of the string is printed.

Now, coming to:

cout << s+1 << endl;

As s, again, is a pointer to a null terminated string and points to the first const char of the string, if we do some arithmetics on it by adding one, we will just increment the value of s, the pointer, towards the succeeding const char. But keeping in mind that, as you have declared a pointer to a sequence of const char these chars will be located somewhere else than you might think. Observe your last line:

cout << &(s+1) << endl

It will give you an error, because (s+1) is an rvalue, which basically means that it has not a defined memory address. It might be stored into some registry location for the duration of the computation. It is basically like saying &1, of course, 1 has not pointer.

Upvotes: 2

Related Questions