A 10 minute read this time.
Intro
Soon enough the student will know the basics of pointers. Below I will create a
character array, and a pointer that will point to this array:
Code:
char FirstArray[20];
char* pToArray;
pToArray = FirstArray;
This is what we are talking about in TIP #4.
A Tiny Program
Let's write a program that does the following:
Create an infinite loop that keeps asking for (console) input. When some input is given, output to screen, showing the entered word letter by letter.
One special requirement: Use pointers only in the loop!
Okidoky. Here is our neat attempt:
Code:
#include <iostream>
#include <cstring>
int main()
{
char FirstArray[20];
char* pToArray;
pToArray = FirstArray;
for(;;) //Forever.
{
std::cout<<"Enter a string: "<<std::endl;
std::cin>>FirstArray;
while(*pToArray)
{
std::cout<<*pToArray<<std::endl;
*pToArray++;
}
}
return (0);
}
The Problem
Ay, this may or this may not work. The standard doesn't guaruantee it. Why should it anyway?
The first time the loop runs, all works well. But the next time, it gets buggy. The reason is that the pointer
pToArray is increased by 1 each iteration. So after the last iteration (depends on entered word length),
pToArray may point to anywhere.
The Solution
The solution is to move the pointer assignment inside the main loop. This way you'll be sure that on each iteration, the pointer points to a valid location, namely the start of data pointed by
FirstArray:
Code:
#include <iostream>
#include <cstring>
int main()
{
char FirstArray[20];
char* pToArray;
for(;;) //Forever.
{
pToArray = FirstArray; // !
std::cout<<"Enter a string: "<<std::endl;
std::cin>>FirstArray;
while(*pToArray)
{
std::cout<<*pToArray<<std::endl;
*pToArray++;
}
}
return (0);
}
//-----------
The Moral
Learn to keep
ACTIVELY track of the behaviour of individual pointers as well as their relationships with eachother. One good way is to actually sketch the memory layout on a piece of paper at key code execution points. Do this when the tough gets going. Pointer Rambo's don't exist.