The Wayback Machine - https://web.archive.org/web/20240717024547/https://www.geeksforgeeks.org/unusual-behaviour-with-character-pointers/
Open In App

Unusual behaviour with character pointers

Last Updated : 03 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 cout behaves differently with character pointers, and then the reason and the working mechanism behind it will be discussed.

Example 1:

C++




// 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.

Example 2:

C++




// 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.

Example 3:

C++




// C++ program to illustrate difference
// between behaviour of character and
// character pointer
#include <iostream>
using namespace std;
  
// Drive Code
int main()
{
    char c = '$';
    char* p = &c;
  
    cout << c << endl;
    cout << p << endl;
}


Output:

abc
a
a

Output:

Explanation:
In the above example, c is a simple character variable and it prints the value stored in it as expected. p being a character pointer when used with cout, results in the printing of each and every character till a null character is encountered. Thus, some garbage value is being printed after ‘$’. This simply means that in the memory the null character was placed after the ‘a’ character (since in this case, there is no automatic storing of a null character after the useful piece of data is finished unlike character arrays) and so it stops printing and gives the obtained output.

Reason behind unusual behaviour with character pointers:

The reason for this lies in the concept of Operator Overloading. ‘<<‘ operator is overloaded for different types of inputs. In the case of const void* overload, it prints just the address. But for const char* overload, it starts printing each and every character till it encounters a null character (treating the input as C — style string).

Example 4:
 

C++




// C++ program to illustrate
// printing of character array
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    // Character array
    char c[] = "abc";
  
    // print value of c, c[0] and *c
    cout << c << endl;
    cout << c[0] << endl;
    cout << *c << endl;
}


Output:

abc
a
a

Explanation:In the above example:

  • Only ‘c’ with cout is treated as const char * and << operator overload for such input is called and thus every character is printed until null character.
  • When using c[0], i.e., *(c + 0), it simply dereferences the particular memory location and prints the value stored at that location only.
  • Similarly, for *c which is same as *(c + 0).

NOTE: The unusual behaviour can be rectified if the output is type casted into something which will not be treated as C-style string.
Example 5:

C++




// C++ program to illustrate behaviour
// of typecasted character pointer
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    char c[] = { "abc" };
    char* b = c;
    cout << (void*)b;
}


Output:

0x7ffe66f7f420

Explanation:
In the above example, the base address of the character array is obtained in the output.

Utilization of unusual behaviour with character pointers:

Given a string, print the pattern as shown in the following example:

C++




// C++ program to illustrate the
// utilization of unusual behaviour
// of character pointer
#include <iostream>
using namespace std;
  
// Function that prints the pattern
void printPattern(char* ch)
{
    // Base Condition
    if (*ch == '\0')
        return;
  
    // Recursion function call after
    // excluding the current character
    printPattern(ch + 1);
  
    // Print the whole string starting
    // from base address stored in 'ch'
    cout << ch << endl;
}
  
// Driver Code
int main()
{
    char ch[] = { "abcd" };
  
    // Function Call
    printPattern(ch);
  
    return 0;
}


Output:

d
cd
bcd
abcd


Similar Reads

Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers but the address bus was 20-bits wide. Due to this, the registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were used in C to store the addresses. There are old co
4 min read
Program to reverse an array using pointers
Prerequisite : Pointers in C/C++ Given an array, write a program to reverse it using pointers . In this program we make use of * operator . The * (asterisk) operator denotes the value of variable . The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer .
4 min read
Program to Reverse a String using Pointers
Given a string, the task is to reverse this String using pointers. Examples: Input: Geeks Output: skeeG Input: GeeksForGeeks Output: skeeGroFskeeG Approach: This method involves taking two pointers, one that points at the start of the string and the other at the end of the string. The characters are then reversed one by one with the help of these t
2 min read
Difference between pointer to an array and array of pointers
Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to access the components of the array. int a[3] = {3, 4, 5 }; int *ptr = a; We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer that can point to whole array rather than just a single component of the
4 min read
Features and Use of Pointers in C/C++
Pointers store the address of variables or a memory location. Syntax: datatype *var_name; Example: pointer "ptr" holds the address of an integer variable or holds the address of memory whose value(s) can be accessed as integer values through "ptr" int *ptr; Features of Pointers: Pointers save memory space.Execution time with pointers is faster beca
2 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read
How many levels of pointers can we have in C/C++
Prerequisite: Pointer in C and C++, Double Pointer (Pointer to Pointer) in CA pointer is used to point to a memory location of a variable. A pointer stores the address of a variable and the value of a variable can be accessed using dereferencing of the pointer. A pointer is generally initialized as: datatype *variable name; This above declaration i
7 min read
Why do we need reference variables if we have pointers
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be de referenced with * operator to access the memory location it points to.References: A Reference can be called as a constant pointer that becomes de referenced implicitly. When we access the reference it means we are accessing the storage.Why do w
4 min read
C++ Modify Pointers
Prerequisite: Pointer in C++ Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let's check the approach we are going to use. Approach: In the below
2 min read
Array of Pointers in C
In C, a pointer array is a homogeneous collection of indexed pointer variables that are references to a memory location. It is generally used in C Programming when we want to point at multiple memory locations of a similar data type in our C program. We can access the data by dereferencing the pointer pointing to it. Syntax: pointer_type *array_nam
5 min read
Practice Tags :
three90RightbarBannerImg