Home arrow Practices arrow Page 7 - What`s the Address? Pointers

Returning Pointers from Function s - Practices

The name "pointer" describes the job of the item; a pointer "points" to another variable or constant. Some tasks in C++ are easier to do with pointers; others would be utterly impossible without pointers. This article discusses how to create and work with pointers in C++. It is taken from chapter 11 of the book C++ Demystified, written by Jeff Kent (McGraw-Hill/Osborne, 2004; ISBN: 0072253703).

TABLE OF CONTENTS:
  1. What`s the Address? Pointers
  2. Assigning a Pointer the Address of a Variable or Constant
  3. The Array Name as a Constant Pointer
  4. Incrementing a Pointer
  5. Passing an Array Using Pointer Notation
  6. Dynamic Memory Allocation
  7. Returning Pointers from Function s
  8. Summary
By: McGraw-Hill/Osborne
Rating: starstarstarstarstar / 16
September 01, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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

#include <iostream <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 <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.



 
 
>>> More Practices Articles          >>> More By McGraw-Hill/Osborne
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PRACTICES ARTICLES

- Calculating Development Project Costs
- More Techniques for Finding Things
- Finding Things
- Finishing the System`s Outlines
- The System in So Many Words
- Basic Data Types and Calculations
- What`s the Address? Pointers
- Design with ArgoUML
- Pragmatic Guidelines: Diagrams That Work
- Five-Step UML: OOAD for Short Attention Span...
- Five-Step UML: OOAD for Short Attention Span...
- Introducing UML: Object-Oriented Analysis an...
- Class and Object Diagrams
- Class Relationships
- Classes

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: