Practices
  Home arrow Practices arrow Page 5 - What`s the Address? Pointers
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 
 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

    Ziff Davis Enterprise Virtual Tradeshows: Hot Topics, Cutting Edge Technology, Real-time Interaction with IT Professionals. Learn more at ziffdavisvts.com

    What`s the Address? Pointers - Passing an Array Using Pointer Notation
    (Page 5 of 8 )

    In Chapter 10, we employed the following program that used one function to assign values to the array and another function to display values from the array, rather than doing all that work in the main function. 

    #include <iostream>
    using namespace std;
    void assignValues(int[], int);
    void displayValues(int[], int);
    const int MAX = 3;

    int main ()
    {
      int testScore[MAX];
      assignValues(testScore, MAX);
      displayValues(testScore, MAX);
      return 0;
      }

      void assignValues(int tests[], int num)
      {
        for (int i = 0; i < num; i++)
          {
    cout << "Enter test score #" << i + 1 << ": "; cin >> tests[i];
          }
      }

      void displayValues(int scores[], int elems)
     
    {
        for (int i = 0; i < elems; i++)
         
    {
            cout << "Test score #" << i + 1 << ": " << scores[i] << endl;
      }
    }

    As discussed in Chapter 10, the two functions, assignValues and displayValues, passed their first argument, the array, by address. An argument passed by address can be changed in the calling function (here main) by the called function (here assignValues) just as if the argument had been passed by reference. Thus, the assignValues function changed the value of the testScore array in main by assigning values to the elements of that array.

    The function prototypes and headers of the assignValues and displayValues functions used a subscript [] to indicate that an array is being passed. However, you can also use pointer notation—for instance, asterisk * instead of a subscript []—as the following example demonstrates:

    #include <iostream>
    using namespace std;
    void assignValues(int*, int);
    void displayValues(int*, int);
    const int MAX = 3;

    int main ()
    {
      int testScore[MAX]; assignValues(testScore, MAX);
      displayValues(testScore, MAX);
      return 0;
    }

    void assignValues(int* tests, int num)
    {
      for (int i = 0; i < num; i++)
      { 
        cout << "Enter test score #" << i + 1 << ": ";
        cin >> tests[i];
      }
    }

    void displayValues(int* scores, int elems)
    {
      for (int i = 0; i < elems; i++)
      {
        cout << "Test score #" << i + 1 << ": " << scores[i] << endl;
      }
    }

    The following comparison of the prototypes of the assignValues function using subscript and pointer notation, respectively, shows that the only difference is whether a subscript [] or an asterisk * is used to denote that the argument is an array:

    void assignValues(int[], int);
    void assignValues(int*, int);

    Similarly, the following comparison of the function headers of the assignValues function using subscript and pointer notation, respectively, shows that the only difference is whether a subscript [] or an asterisk * is used to denote that the argument is an array. This time, however, the asterisk precedes the variable name, whereas the subscript follows the variable name.

    void assignValues(int tests[], int num)
    void assignValues(int* tests, int num)

    Whether you use subscript or pointer notation to pass an array really is a matter of preference. There is no programming advantage one way or the other. However, the next section discusses a situation in which subscript notation is not an option, so pointer notation is the only choice.

    Passing a Single Variable Using Pointer Notation

    Passing an array name by address is relatively simple because the value of the array name is an address. However, you may often want to pass a single variable by address. By single variable I don’t mean a variable that is unmarried, but instead, for example, an int as opposed to an int array. 

    With a single variable, subscript notation is not an option. Subscripts make sense only with an array. Rather, you need to use pointer notation to pass a single variable by address.

    Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function—only the syntax is different. For comparison, let’s start with the following program from Chapter 9 that passes the variable to be doubled by reference:

    #include <iostream <iostream>>
    using namespace std;
    void doubleIt(int&);

    int main ()
    {
    int num;
      cout << "Enter number: ";
      cin >> num;
      doubleIt(num);
      cout << "The number doubled in main is " << num << endl;
      return 0;
    }

    void doubleIt (int& x)
    {
      cout << "The number to be doubled is " << x << endl;
      x*=2;
      cout << "The number doubled in doubleIt is " << x << endl;
    }

    Here is some sample input and output:

    Enter number: 3
    The number to be doubled is 3
    The number doubled in doubleIt is 6
    The number doubled in main is 6

    Let’s now modify this program so it passes the variable to be doubled by address instead of by reference:

    #include <iostream>
    using namespace std;
    void doubleIt(int*);

    int main ()
    {
      int num;
      cout << "Enter number: ";
      cin >> num;
      doubleIt(&num);
      cout << "The number doubled in main is " << num << endl;
      return 0;
    }

    void doubleIt (int* x)
      {
      cout << "The number to be doubled is " << *x << endl;
      *x *= 2;
      cout << "The number doubled in doubleIt is " << *x << endl;
    }

    There are four syntax differences between these two programs.

    1. In the function prototype, you use an ampersand (&) for passing by reference but an asterisk (*) for passing by address:

    void doubleIt(int&); // by reference
    void doubleIt(int*); // by address

    2. Similarly, in the function header, you use an ampersand (&) for passing by reference but an asterisk (*) for passing by address:

    void doubleIt (int& x) // by reference
    void doubleIt (int* x) // by address

    3. When you call the function, you don’t need the address operator (&) for passing by reference, but you do need one for passing by address since you are supposed to be passing by the address of x.:

    doubleIt(num); // by reference
    doubleIt(&num); // by address

    4. In the body of the called function, you don’t need to dereference the argument when you pass it by reference, but you do need to when you pass by address since x, being passed by address, is not a value but is instead a pointer:

    // by reference -no dereference

      cout << "The number to be doubled is " << x << endl;
      x*=2;
      cout << "The number doubled in doubleIt is " << x << endl;
    }
    // by address -need to dereference
    {
      cout << "The number to be doubled is " << *x << endl;
      *x *= 2;
      cout << "The number doubled in doubleIt is " << *x << endl;
    }

    You may legitimately be wondering why, with a single variable argument, I would want to pass it by address when the syntax for passing it by reference seems easier. The pat answer I give my students is that there are certain sadistic computer science teachers (I’m not mentioning any names here) who insist their students pass by address to make them suffer. All kidding aside though, there are actually certain library functions that do use pass by address. Additionally, when using dynamic memory allocation and returning pointers from functions (to be covered in the following sections), passing by address may be the only option.

    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




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