C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Pointers in C++  >  Arrays and Pointers
 

While discussing arrays in the previous session, it was mentioned that the name of the array holds the address of the first element in that array. Therefore, in the declartion,

char cStr[10];

dStr holds the address of cStr[0]. A pointer is also defined as a variable that holds the address of another variable. Therefore, the name of an array is actually a pointer. Program 5.3 manipulates an array through a pointer.

//Program 5.3
//Manipulation of an array through a pointer
char cStr[28] = "Welcome to wherever you are.";
#include<iostream.h>
void main()
{
char *cPtr;
cout<<"The string is: "<<cStr<<endl;
cPtr = cStr; //cPtr is pointing to wherever cStr is pointing to
cout<<"The string is: "<<cPtr<<endl;
}


The output of Program 5.3 is:

The string is Welcome to wherever you are.
The string is Welcome to wherever you are.

Although Program 5.3 gives an impression that arrays and pointers are the same, there is a subtle difference between the two. Both cStr and cPtr are pointers to char data type. However, cStr as a pointer is constant, which means it always points to the first element in the array of 28 characters. Therefore, the value of cStr cannot be changed. But cPtr as a pointer is dynamic. It can be made to any address in memory.

To understand the concept better, consider the following example:

//Program 5.4
//This program demonstrates the dynamic nature of pointers
#include<iostream.h>
char cStr[] = "Mad dogs go to heaven";
void main()
{
char *cPtr, cVar = 'A';
cPtr = cStr; //cPtr and cStr both point to the same location, that is the first element of the array cStr
cout<<cPtr<<endl;
cPtr = &cVar; //Now cPtr is pointing to the variable cVar
cout<<*cPtr;
}


The output of Program 5.4 is:

Mad dogs go to heaven
A

 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.