C++ Pointer to Char Array

Spread the love

C++ Pointer to Char Array examples below.

char var[4] = {‘1′,’2′,’3′,’\0’};

char *ptr; // c++ pointer to a char array

ptr = &var[0]; // points to the start of the array

std::cout << “Address of var is ” << &var << std::endl;

std::cout << “Value of var is ” << *ptr << std::endl;

Last std::cout will print all the characters starting from position 0. Other users have asked why: we dont know. That’s the way the std::cout author wanted it, is our best guess

Why we need C++ Pointers and References

C++ pointers are not difficult to learn. In truth, there are a few C++ tasks that are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, which are almost impossible to do without our pointy friends.

Every variable is a memory location and every memory location has an address. In the case of the char pointer and char array, note that the pointer points to the beginning of the address given, whether that is the beginning of the char array or half way thru like position 4 myArray[3]. std::cout will print from position 4, all the way until it hits the \0 or null data.

Each of these specific addresses can be accessed by using the ampersand (&) operator. Code below will print the address of the variables of integer mAnt and the char array of mAnt2. 

Address of mAnt variable: 0x7c1b1ed8138c

Address of mAnt2 variable: 0x7c1b1ed81390

So now that we have finished with Addresses, can we move on?

Yeah, but not really. Lets take a look at our Pointy friends but this doesn’t mean that we are finished with Addresses otherwise known as C++ References, right?

C++ Pointer to Char Array – In Terms of Chars

A C or C++ pointer associated with a char array is a variable of char type that points to an Address or Reference. Oh my gosh, so we aren’t finished with Addresses yet? Ok, so how does this work then?

C++ Pointer to Char Array – Sample Code

#include <iostream>
using namespace std;
int main () {
    char *ptr;
    char *ptr1;
    char minAlpha[5] = {'A','B','C','D','\0'};
    ptr = &amp;minAlpha[0];
    ptr1 = &amp;minAlpha[0]+1;
    cout << "Value of mini Alphabet position 0 =" << ptr << endl;
    cout << "Value of mini Alphabet position 1 =" << ptr1 << endl;

   return 0;

Value of mini Alphabet position 0 =ABCD

Value of mini Alphabet position 1 =BCD

c++ pointer to char array. Image shows source codes for 2 c++ pointers *ptr and *ptr1. The output of the code is shown below

Homework — Pointer to a position in the Char Array

  • 1) The last example above is really short. Please memorize
  • 2) From memory rewrite the code above into your c++ compiler/editor
  • 3) Add a 3rd pointer and point it to the ‘C’ in the array
  • 4) Add a 3rd cout statement and refer to the 3rd pointer

Next Lesson 9, C++ Pointer to a String Array

A Good place to learn more about c++ pointers to char arrays etc

Go Back to Top of C++ Pointer to Char Array Document