Home arrow C++ arrow Page 8 - What`s the Address? Pointers
C++

What`s the Address? Pointers


A pointer simply points to another variable or constant. Though they have a reputation for being difficult to learn, they really are not that hard. This is fortunate, becuase pointers are very important to programming. This article explains how to create and work with pointers in C++. It is excerpted from chapter 11 of the book C++ Demystified, written by Jeff Kent (McGraw-Hill, 2004; ISBN: 0072253703).

Author Info:
By: McGraw-Hill/Osborne
Rating: 5 stars5 stars5 stars5 stars5 stars / 27
August 11, 2005
TABLE OF CONTENTS:
  1. · What`s the Address? Pointers
  2. · Assigning a Value to a Pointer
  3. · Pointer as a Variable
  4. · Incrementing a Pointer
  5. · Passing an Array Using Pointer Notation
  6. · Passing a Single Variable Using Pointer Notation
  7. · Dynamic Memory Allocation
  8. · Returning Pointers from Functions
  9. · Summary

print this article
SEARCH DEVARTICLES

What`s the Address? Pointers - Returning Pointers from Functions
(Page 8 of 9 )

In Chapter 10, you learned several ways to initialize a character array. The following program shows you an additional way:

#include <iostream>
using namespace std;
char * setName();
int main (void)
{
  
char* str = "Jeff Kent";
  
cout << str;
  
return 0;
}

With some sample input and output:

Enter your name: Jeff Kent
Your name is Jeff Kent

The key statement is

 char* str = "Jeff Kent";

This statement is almost the same as:

 char str[] = "Jeff Kent";

In both statements, str is a character pointer, and implicit array sizing is used. The difference is that str in the first statement (char* str) is a variable pointer whereas str in the second statement (char str[]) is a constant pointer.

Returning a Pointer to a Local Variable (Not a Good Idea)

Now, following the advice in Chapter 9 to make your program more modular, you try to write a separate function, setName, to obtain the user input. The setName function creates a character array, assigns user input to that array using the getline function of the cin object, and then returns a pointer to that character array. The address which is returned by the setName function then is assigned to the character pointer str in main. The following program implements this concept:

#include <iostream>
using namespace std;
char * setName();
int main (void)
{
char* str = setName();
cout << str;
return 0;
}
char* setName (void)
{
char name[80];
cout << "Enter your name: ";
cin.getline (name, 80);
return name;
}

The following is some sample input and output:

Enter your name: Jeff Kent
..................D ............   ........8   ........

While the outputted name is interesting, it certainly would be difficult to write, and in any event, it is not what I inputted. What went wrong is that the pointer returned by the setName function points to a local character array whose lifetime ended when that function finished executing and returned control to main.

Accordingly, the indicated solution is to extend the lifetime of that character array to the life of the program execution itself. Of course, one way to accomplish this is by making the character array a global variable, but as you should recall from Chapter 9, there are other and better alternatives.

Returning a Pointer to a Static Local Variable

One superior alternative is to make the character array in setName static, as in the following program:

#include <iostream>
using namespace std;
char * setName();
int main (void)
{
char* str = setName();
cout << str;
return 0;
}
char* setName (void)
{
   static char name[80];
   cout << "Enter your name: ";
   cin.getline (name, 80);
   return name;
}

The output from the following sample input now looks much better:

Enter your name: Jeff Kent
Jeff Kent

This works because while the scope of a static local value is limited to the function in which it is declared, its lifetime is not similarly limited, but instead lasts as long as the execution of the program. Therefore, the pointer returned by the setName function points to a local character array whose lifetime, since it was declared with the static keyword, persisted after the setName function finished executing and returned control to main.

Returning a Pointer to a Dynamically Created Variable

Another alternative, which you learned in this chapter, is dynamic memory allocation:

#include <iostream>
using namespace std;
char * setName();
int main (void)
{
char* str;
str = setName();
cout << str;
delete [] str;
return 0;
}
char* setName (void)
{
char* name;
name = new char[80];
cout << "Enter your name: ";
cin.getline (name, 80);
return name;
}

This works because the pointer returned by the setName function points to a character array whose lifetime, since it was declared using dynamic memory allocation, persisted after the setName function finished executing and returned control to main.

As discussed in the previous section, if you dynamically allocate memory inside a function using a local pointer, then when the function terminates, the pointer will be destroyed but the memory will remain, orphaned since there is no longer a way of accessing it for the remainder of the program. This problem is avoided in this program since the local pointerís address is returned by the setName function and is assigned in main to another pointer variable, str. The pointer variable str then is used at the end of main with the delete operator to deallocate the character array which was dynamically allocated in the setName function.

This is an example where different pointers point to the same memory address. However, in the case of dynamically created memory, once you use one of those pointers with the delete operator, donít make the common mistake of using another of the pointers with the delete operator. You should only use the delete operator with a pointer that points to dynamically created memory. If that dynamically allocated memory already has been deallocated using the delete operator, using the delete operator the second time will lead to unpredictable results.


blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials