Thread: Pointers

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Registered User
    Join Date
    Oct 2010
    Posts
    18
    Edit:
    Given responses to my reply below I've updated my post.
    Writing bad code ad-hoc is what I get for being in a hurry. Hehe.
    --

    There's also significant performance benefits. You can pass a pointer to the first element of an array, instead of passing an entire array.

    Code:
    // fail.
    void function (int data[100])
    	{ data[99]; }
    
    // win!
    void function (int *data, int size)
    	{ data[size-1]; }
    Better yet in C++ vectors are handy.

    Code:
    // win!
    void function (vector<int> *data)
    	{ data->at(data->size() - 1); }
    You can get even fancier with more complex projects where you're managing an array of large objects, instead of storing objects within the array store pointers to the objects instead. That way if any copies of the array occur it's only copies of the pointers and not a set of giant objects.

    Code:
    // win!
    void function (vector<object *> *objects)
    	{ objects->at(objects->size() - 1)->method(); }
    
    // not as win, but not as fail either!
    void function (vector<object *> objects)
    	{ objects.at(objects.size() - 1)->method(); }
    
    // works, but not great if performance matters.
    void function (vector<object> objects)
    	{ objects.at(objects.size() - 1).method(); }
    So pointers/references can make working with arrays more flexible, practical, efficient, etc.
    Last edited by syneii; 12-10-2010 at 03:36 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Arrays with pointers
    By Niels_M in forum C Programming
    Replies: 18
    Last Post: 07-31-2010, 03:31 AM
  2. size of struct with pointers and function pointers
    By sdsjohnny in forum C Programming
    Replies: 3
    Last Post: 07-02-2010, 05:19 AM
  3. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  4. pointers to arrays
    By rakeshkool27 in forum C Programming
    Replies: 1
    Last Post: 01-24-2010, 07:28 AM
  5. Pointers pointers pointers....
    By G'n'R in forum C Programming
    Replies: 11
    Last Post: 11-02-2001, 02:02 AM