Unusual behaviour with character pointers

Configurare noua (How To)

Situatie

In C++, cout shows different printing behaviour with character pointers/arrays unlike pointers/arrays of other data types. So this article will firstly explain how coutbehaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed.

Solutie

Pasi de urmat
// C++ program to illustrate difference
// between behaviour of integer pointer
// and character pointer
#include <iostream>
using namespace std;
// Driver Code
int main()
{
// Integer array
int a[] = { 1, 2, 3 };
// Character array
char ch[] = “abc”;
// Print the value of a and b
cout << a << endl;
cout << ch << endl;
return 0;
}
Output:

0x7ffc623e56c0
abc

Explanation:
From the above code, it is clear that:

  • When using the integer pointer to an array, cout prints the base address of that integer array.
  • But when the character pointer is used, cout prints the complete array of characters (till it encounters a null character) instead of printing the base address of the character array.
// C++ program to illustrate behaviour
// of character pointer pointing to
// character array
#include <iostream>
using namespace std;
// Driver Code
int main()
{
// Character array b
char b[] = “abc”;
// Pointer to character array
char* c = &b[0];
// Print the value of c
cout << c << endl;
}
Output:

abc

Explanation:
In this example as well, the character type pointer c is storing the base address of the char array b[] and hence when used with cout, it starts printing each and every character from that base address till it encounters a NULL character.

Tip solutie

Permanent

Voteaza

(5 din 11 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?