Explain between int and char pointers

I am using Microsoft Visual studio 2010.
Can someone explain me following behavior?

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	char  a[]={'h','e','l','l','o','1','2'};
	char * q=a;
	cout <<q<<endl; //prints hello12

	int b[] ={1,2};
	int * p=b;
	cout <<p<<endl; //print memory address ?? why

	return 0;
}
char* pointing to a char array is often used as strings. For that reason it is convenient if printing a char* prints the whole string so we don't have to iterate over the whole string each time we want to print it. int* is not often used like that so it make more sense to print the address in that case.
Because the char pointer follows the C-string convention, while the int pointer is nothing more than a regular pointer.
Last edited on
To be safe the c string should be null terminated
char a[]={'h','e','l','l','o','1','2','\0'};
This behavior is only when I use
 
cout << q <<endl;
hello12

When using
 
cout <<*q<<endl;
h


It behaves like normal pointer behavior printing only 'h';

So it was designed to print full array of character when address of char is being printed??
Yes.
The char pointer is essentially a regular pointer pointing to a memory address, like others.
It just behaves smart when being printed by convention.
Topic archived. No new replies allowed.