C++
  Home arrow C++ arrow Page 8 - What`s the Address? Pointers
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

What`s the Address? Pointers
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 14
    2005-08-11

    Table of Contents:
  • What`s the Address? Pointers
  • Assigning a Value to a Pointer
  • Pointer as a Variable
  • Incrementing a Pointer
  • Passing an Array Using Pointer Notation
  • Passing a Single Variable Using Pointer Notation
  • Dynamic Memory Allocation
  • Returning Pointers from Functions
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More C++ Articles
    More By McGraw-Hill/Osborne


     

    Buy this book now. This article is excerpted from chapter 11 of the book C++ DeMYSTifieD, written by Jeff Kent (McGraw-Hill, 2004; ISBN: 0072253703). Check it out at your favorite bookstore. Buy this book now.

    C++ ARTICLES

    - 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++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek