Pointers

This is a discussion on Pointers within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> using namespace std; int main() { int x; // I understand this is an integer and it's ...

  1. #1
    Registered User MrMatt027's Avatar
    Join Date
    Nov 2010
    Location
    USA, Florida
    Posts
    21

    Pointers

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      int x;            // I understand this is an integer and it's named x.
      int *p;           // I understand this is a pointer to an integer.
    
      p = &x;           // I understand this read p and "assign the address of x to p".
      cin>> x;          // I understand this put a value in x, we could also use *p here.
      cin.ignore(); 
      cout<< *p <<"\n"; // I understand this outputs the value of "p which is equal to x".
      cin.get();
    }
    I understand all of this example code.
    What I don't understand is why they are used. Couldn't one just use a variable?
    I've viewed the tutorials on 'pointers' numerous times and visited multiple other sites that explained it, but I'm still confused.
    Does anyone know anywhere I can get a better explanation of what a pointer is and why they're used?

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,643
    In short, a world without pointers would make things like linked lists impossible, and many other things, well, rather difficult. Wikipedia gives a decent overview here. Eventually, experience will help clarify things, too.
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    10
    I hope that helps

    A pointer is the memory address of a variable. Recall that the computer’s
    memory is divided into numbered memory locations (called bytes), and that
    variables are implemented as a sequence of adjacent memory locations. Recall
    also that sometimes the C++ system uses these memory addresses as names for
    the variables. If a variable is implemented as, say, three memory locations,
    then the address of the first of these memory locations is sometimes used as a
    name for that variable. For example, when the variable is used as a call-by-
    reference argument, it is this address, not the identifier name of the variable,
    that is passed to the calling function.
    An address that is used to name a variable in this way (by giving the address
    in memory where the variable starts) is called a pointer because the address can
    be thought of as “pointing” to the variable. The address “points” to the variable
    because it identifies the variable by telling where the variable is, rather than
    telling what the variable’s name is. A variable that is, say, at location number
    1007 can be pointed out by saying “it’s the variable over there at location 1007.”
    Pointers are like call-by-reference argument in a function call, the function is given this argument variable in the form of a pointer to the variable. This is an important and powerful use for pointers, but it is done automatically for you by the C++ system.
    Pointer Variables
    A pointer can be stored in a variable. However, even though a pointer is a
    memory address and a memory address is a number, you cannot store a pointer
    in a variable of type int or double. A variable to hold a pointer must be declared
    to have a pointer type. For example, the following declares p to be a pointer
    variable that can hold one pointer that points to a variable of type double:

    double *p;

    The variable p can hold pointers to variables of type double, but it cannot
    normally contain a pointer to a variable of some other type, such as int or
    char. Each variable type requires a different pointer type.
    In general, to declare a variable that can hold pointers to other variables
    of a specific type, you declare the pointer variable just as you would declare an
    ordinary variable of that type, but you place an asterisk in front of the variable
    name. For example, the following declares the variables p1 and p2 so that they
    can hold pointers to variables of type int; it also declares two ordinary
    variables, v1 and v2, of type int:

    int *p1, *p2, v1, v2;

    There must be an asterisk before each of the pointer variables. If you omit the
    second asterisk in the previous declaration, then p2 will not be a pointer
    variable; it will instead be an ordinary variable of type int. The asterisk is the
    same symbol you have been using for multiplication, but in this context it has
    a totally different meaning.
    When discussing pointers and pointer variables, we usually speak of
    pointing rather than speaking of addresses. When a pointer variable, such as p1,
    contains the address of a variable, such as v1, the pointer variable is said to
    point to the variable v1 or to be a pointer to the variable v1.
    Pointer variables, like p1 and p2 declared earlier, can contain pointers to
    variables like v1 and v2. You can use the operator & to determine the address
    of a variable, and you can then assign that address to a pointer variable. For
    example, the following will set the variable p1 equal to a pointer that points
    to the variable v1:
    p1 = &v1;

    Declaring

    You now have two ways to refer to v1: You can call it v1 or you can call it “the
    variable pointed to by p1.” In C++, the way that you say “the variable pointed to
    by p1” is *p1. This is the same asterisk that we used when we declared p1, but now
    it has yet another meaning. When the asterisk is used in this way, it is often called
    the dereferencing operator, and the pointer variable is said to be dereferenced.
    Putting these pieces together can produce some surprising results. Consider
    the following code:
    v1 = 0;
    p1 = &v1;
    *p1 = 42;
    cout << v1 << endl;
    cout << *p1 << endl;
    This code outputs the following to the screen:
    42
    42

    Basically

    A pointer is an address, and an address is an integer, but a pointer is not
    an integer.C++ insists that you use a
    pointer as an address and that you not use it as a number. A pointer is not
    a value of type int or of any other numeric type. You normally cannot
    store a pointer in a variable of type int. If you try, most C++ compilers will
    give you an error message or a warning message. Also, you cannot perform
    the normal arithmetic operations on pointers. (You can perform a kind of
    addition and a kind of subtraction on pointers, but they are not the usual
    integer addition and subtraction.)

  4. #4
    Registered User MrMatt027's Avatar
    Join Date
    Nov 2010
    Location
    USA, Florida
    Posts
    21
    Oh I see, I think understand now. Thank you. I was over thinking this whole thing and probably getting ahead of myself in the process. The hexadecimals and the ability to "dynamically accolate memory" threw me off quite a bit in some of these other tutorials.

    So a pointer can access or change a value wherever it is?
    (Be it in a different scope, different function, different header file, array,... whereas a variable cannot?)
    Last edited by MrMatt027; 12-09-2010 at 09:30 PM.

  5. #5
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Quote Originally Posted by MrMatt027 View Post
    So a pointer can access or change a value wherever it is?
    (Be it in a different scope, different function, different header file, array,... whereas a variable cannot?)
    Well, yes, but that "variable" or memory it points to has to exist in the first place.
    You should be careful about the scope, since variables that go out of scope will be destroyed, so even if you have a pointer to that variable in some scope, and the pointer will live outside the variable's scope, it will point to invalid data.
    Linked lists is a very good example of where pointers are required.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #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 02:36 PM.

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,643
    Quote Originally Posted by syneii View Post
    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:
    void function (int[100] craptaco) { } // fail.
    void function (int * woohoo) { (*woohoo)[0] ... (*woohoo)[99] } // win!
    So that makes working with arrays more flexible, or vectors, or what ever. You can have a global object that tracks and stores program data, then use pointers as references those structures instead of copying the entire thing in to a function scope.

    There's a lot of clever and creative uses for pointers that simply make managing large or complex objects much more efficient.
    Except...that isn't valid C++ code...
    Code:
    if( numeric_limits< byte >::digits != bits_per_byte )
        error( "program requires bits_per_byte-bit bytes" );
    24bbs.cpp

  8. #8
    Registered User MrMatt027's Avatar
    Join Date
    Nov 2010
    Location
    USA, Florida
    Posts
    21
    Quote Originally Posted by Elysia View Post
    Well, yes, but that "variable" or memory it points to has to exist in the first place.
    You should be careful about the scope, since variables that go out of scope will be destroyed, so even if you have a pointer to that variable in some scope, and the pointer will live outside the variable's scope, it will point to invalid data.
    Linked lists is a very good example of where pointers are required.
    Tyvm, you've cleared up some other questions I've been asking myself.
    Last edited by MrMatt027; 12-10-2010 at 10:13 PM.

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Quote Originally Posted by syneii View Post
    There's also significant performance benefits. You can pass a pointer to the first element of an array, instead of passing an entire array.

    void function (int[100] craptaco) { } // fail.
    void function (int * woohoo) { (*woohoo)[0] ... (*woohoo)[99] } // win!

    So that makes working with arrays more flexible, or vectors, or what ever. You can have a global object that tracks and stores program data, then use pointers as references those structures instead of copying the entire thing in to a function scope.

    There's a lot of clever and creative uses for pointers that simply make managing large or complex objects much more efficient.
    The first syntax should be
    Code:
    void function (int craptaco[100]) { } // fail.
    and is identical to the second syntax (they mean the same thing).

    However, what you are proposing is incredibly dangerous because you don't know the size. I won't correct it because I know this is an example. Just keep that in mind.
    Also, the code is incorrect, because (*woohoo)[0] should be woohoo[0], and so on.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Oct 2010
    Posts
    18
    Appreciate the replies, unfortunately I was responding in haste and had to leave before really evaluating what I wrote. I should have not hit reply when I did, in any case I went back and changed it all around for clarity.

  11. #11
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Ah, it's better now, if we forget the fact that we probably would use a reference to the vector and not store raw pointers inside the vector. It is an application of pointers, though not the best example.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Oct 2010
    Posts
    18
    It's become second nature for me to default to using pointers, I live dangerously. >:]

    ... it just makes things easier for me where dealing with NULL is a part of the application's design, and yes it does require greater responsibility, but it's worth it to me. In any case I don't think you can logically justify the practice as 'wrong' (I know you didn't say that it is), and you can write perfectly stable software relying on pointers so long as you're thoughtful and consider what conditions can arise in your application.

    But hey, why would you stop at simply suggesting the alternative, it doesn't help our guest any if you don't at least provide an example to demonstrate a safer approach so that the people may learn. ;p
    Last edited by syneii; 12-10-2010 at 03:22 PM.

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    To each his or her own. Still, I would not recommend that to newbies.
    We all have to be careful when giving advice to newbies. They must develop their own habits to stick to. Raw pointers are dangerous.
    This is just an advice. What you do in your own code is really none of my business.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Oct 2010
    Posts
    18
    I don't think that's necessarily a healthy perspective. If I hadn't started off using pointers more often then I would never have really appreciated what exactly can go wrong with a program that isn't well written. In my experience people learn best when they're allowed to trip and fall, it makes the mistake more personal and reinforces learning. If you're sincere you'll support what you believe with more than criticism, you'll provide the alternative to reinforce your point. Considering that, I guess I just indirectly pointed out that I'm selfish, haha.

    What do you think about that?

  15. #15
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,413
    Absolutely. You are correct. Experience comes with learning.
    But also take into account that when writing programs, if you do it wrong, then you will get a lot more bugs, frustration and less reliable software.
    So it's important to learn to get experience, but it's also important to do it the right way to reduce bugs and frustration.

    But more generally, I do believe it is best to train people in the scenarios they are likely to encounter. A linked list is prone to pointer errors and memory leaks if you don't do it properly, so that is an example of where it is a good idea to train yourself.
    But in real life code, you shouldn't--and should not be expected to--handle raw pointers like you do.
    I believe in that if you gain experience if a field where pointers are critical, you gain experience in that field, as well as pointers, and get experience in writing safe and reliable code elsewhere.

    Now. I think I've said my piece, and put out what I wanted to inform about.
    So now, how you approach things in the future is up to you. All I want to ask of you is that you reflect upon what I have mentioned.
    Also feel free to discuss it, of course. No one is flawless, after all, not me or anyone else. I may be wrong in my thinking, as well.
    Last edited by Elysia; 12-10-2010 at 03:34 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

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, 06:28 AM
  5. Pointers pointers pointers....
    By G'n'R in forum C Programming
    Replies: 11
    Last Post: 11-02-2001, 01:02 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21