Question

Why does the following happen?

char str[10]="Pointers";
char *ptr=str;  
cout << str << "\n"; // Output : Pointers
int abc[2] = {0,1 };
int *ptr1 = abc;
cout <<ptr1 << "\n"; // But here the output is an address.
                     // Why are the two outputs different?
Was it helpful?

Solution

As others have said, the reason for the empty space is because you asked it to print out str[3], which contains a space character.

Your second question seems to be asking why there's a difference between printing a char* (it prints the string) and int* (it just prints the address). char* is treated as a special case, it's assumed to represent a C-style string; it prints all the characters starting at that address until a trailing null byte.

Other types of pointers might not be part of an array, and even if they were there's no way to know how long the array is, because there's no standard terminator. Since there's nothing better to do for them, printing them just prints the address value.

OTHER TIPS

1) because str[3] is a space so char * ptr = str+3 points to a space character

2) The << operator is overloaded, the implementation is called depending on argument type:

  • a pointer to an int (int*) uses the default pointer implementation and outputs the formatted address
  • a pointer to a char (char*) is specialized, output is formated as a null terminated string from the value it points to. If you want to output the adress, you must cast it to void*

The empty space is actually Space character after "LAB". You print the space character between "LAB" and "No 5".

Your second question: You see address, because ptr1 is actually address (pointer):

int *ptr1;

If you want to see it's first member (0), you should print *ptr1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top