Confusion while using pointer & string

How the following statements actually working?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()
{
    char *p="i am a string";   //What is it? A pointer variable which can hold an address of a char..isn't it?

    cout<<p<<endl;   //This prints i am a string..why?
    cout<<*p<<endl;  //This prints i why?

    return 0;
}
Array names are basically pointers to the first element in an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
	char *p = "i am a string";   //char array

	cout << p << endl;   //cout char array
	cout << *p << endl;  //This points to the first element in the char array

	cout << strlen(p) << endl;//Length of array

	return 0;
}
Last edited on
If char *p = "i am a string"; is a char array then what is the advantage of using this instead of char p[30]; ??

Why to use *p?
Array names are constant pointers you can't change what they point to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main()
{
	char *p = "i am a string"; 
	char ary[12] = "hello world";

	cout << p << endl; //"i am a string"
	cout << ary << endl;//"hello world"

	p = ary;
	cout << p << endl;//"hello world"
	
	ary = p; //can't do this.

	return 0;
}
 
char *p = "i am a string"; 

"i am a string" is an array of 14 char and p is a pointer to the first char in that array.


 
cout << p << endl;

The << operator has been overloaded to handle char pointers different from other pointer types because it's very common that char pointers are used for strings (especially in C).


 
cout<<*p<<endl;

p points to the first char in the array so *p returns that char and that's why it prints 'i'.
Registered users can post here. Sign in or register to post.