Practices
  Home arrow Practices arrow Page 7 - What`s the Address? Pointers
CIO Insight
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
eWeek
 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? 
PRACTICES

What`s the Address? Pointers
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2005-09-01

    Table of Contents:
  • What`s the Address? Pointers
  • Assigning a Pointer the Address of a Variable or Constant
  • The Array Name as a Constant Pointer
  • Incrementing a Pointer
  • Passing an Array Using Pointer Notation
  • Dynamic Memory Allocation
  • Returning Pointers from Function s
  • 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

    The Web Buyer's Guide is your best source for white papers on a wide range of IT products and services. This Week's Featured White Papers: Help Simplify Virtualization by IBM

    What`s the Address? Pointers - Returning Pointers from Function s
    (Page 7 of 8 )

    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


       · Got good insight on pointers, i found solution to the bug in my code :)
     

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

       

    PRACTICES ARTICLES

    - 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
    - Basic Ideas
    - Choosing the Right Team
    - Trees
    - Basic Array Searching in C++
    - Solving Problems with Recursion

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway