CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Dec 2006
    Posts
    2

    [RESOLVED] C++ Pointers

    Hello, I have read various pointer tutorials but I still don't understand the concept of using them.

    I am using Dev-C++ as my compiler.

    If it would be possible could someone point my into the right direction by providing an example of how a pointer is used correctly.

    I collected this code from a website using pointers.

    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
     int myval = 7;
     int* p_myval = &myval;
     *p_myval = 6;
     cout << myval;
     cin.get();
    }
    This outputs 6.

    Why cannot I just do this?
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
     int myval = 7;
     myval = 6;
     cout << myval;
     cin.get();
    }
    This also outputs 6.

    So I cannot understand the use of pointers, if someone can briefly explain this that would be awesome.

  2. #2
    Join Date
    Dec 2006
    Posts
    33

    Re: C++ Pointers

    In the first example, p_myval is a pointer to myval. That means that when you change the value in p_myval:

    Code:
    *p_myval = 6;
    you are actually changing the value in myval. The example you give is just to demonstrate the concept of pointers but there are few cases where you actually write code like that. Typically pointers are used when you want to pass objects around (without copying the whole object), when you're doing string manipulations (C-style char *), or when you're doing array manipulations.

  3. #3
    Join Date
    Dec 2006
    Posts
    33

    Re: C++ Pointers

    Here's an example (one of many possible uses), lets say you have an object myobj of class C, and a function foo. If I did something inside foo like:

    Code:
    void foo(C obj) {
        obj.changeMe();
    }
    
    C myobj;
    foo(myobj);
    Then nothing would happen to myobj. This is because foo is acting on a [bold]copy[/bold] of myobj.

    However, if you had:

    Code:
    void foo(C *obj) {
        obj->changeMe();
    }
    
    C myobj;
    foo(&myobj);
    Notice 2 things: I am passing in &myobj (a pointer to myobj) and foo is acting on a C *obj (a pointer to an object of type C). Then what happens is that when foo calls changeMe() on obj, it is actually calling changeMe() on myobj! As a result, myobj is changed by foo!

    Hope this helps.


    [EDIT] I realized after typing this that I should have used an int as an example. The same thing works above if you substitute "C with int", "obj.changeMe() with obj = 2" and "obj->changeMe() with *obj = 2", i.e. modifying what obj points to.
    Last edited by panzer2k4; December 19th, 2006 at 11:45 PM.

  4. #4
    Join Date
    Dec 2006
    Posts
    2

    Re: C++ Pointers

    Thanks for taking your time to explain this, it has helped me a ton.

  5. #5
    Join Date
    May 2005
    Location
    Oregon
    Posts
    3,725

    Re: C++ Pointers

    When you want to Perform Calculation on the address of some datatype instead of it's value use Pointers. But Instead of using Pointer if you want you also can proceed with simply STL classes witch is more beneficial for you. Anyway back to Pointers.
    Code:
    if i say
    int i; // so i cn say i is a type of int
    int *i;// in this case i is a type of int pointer.
    a Small Example
    Code:
    #include "stdafx.h"
    #include <iostream.h>
    void Func(int *p)
    {
    *p = 20; //now at address of p value is 20 instead of 10
    }
    int main(int argc, char* argv[])
    {
    int p=10;
    Func(&p);//Here you send the address of p so it's not going to generate a copy of p
    cout<<p;
    return 0;
    }
    if you use simple variable instead of pointer
    Code:
    void Func(int p)
    {
    p = 20; //Here you Change the value of p from 10 to 20.but this value will loose at the time when you return from the Function because scope is local upto Function
    }
    int main(int argc, char* argv[])
    {
    int p=10;
    Func(p);
    cout<<p;
    return 0;
    }
    Now next thing is refrence & .C has two types of argument passing: by address and by value. C++ defines a third argument-passing mechanism: passing by reference. When you pass an argument by reference, the callee gets an alias of the original object and can modify it. In fact, references are rather similar to pointers in their semantics; they're efficient because the callee doesn't get a copy of the original variable.
    Code:
    void Func(int &p) //Only & you have to add here
    {
    p = 20; 
    }
    int main(int argc, char* argv[])
    {
    int p=10;
    Func(p);
    cout<<p;
    return 0;
    }

    Also have alook in MSDN for NULL Pointer ,this pointer etc;

    Thanx
    Last edited by humptydumpty; December 20th, 2006 at 01:28 AM.

  6. #6
    Join Date
    Oct 2006
    Posts
    56

    Re: C++ Pointers

    One thing I've always noticed is that it seems you can do the same thing by passing a reference, as if i were to create a pointer. Is there a performance advantage to one or the other?

  7. #7
    Join Date
    Nov 2006
    Posts
    1,611

    Re: C++ Pointers

    A reference is the same size as a pointer, and offers the same performance benefit with a cleaner syntax.

    For example:
    Code:
    int i = 5;
    
    foo( i );
    The function foo gets a copy of i, and if that function changed i, it changes the copy - which means that after the call to foo, i would still be 5 no matter what foo did to it's copy. The function signature would have been void foo( int );

    Code:
    foo( &i );
    In this example, the address of i is given to foo. The function signature would be void foo( int *);. Now, if foo changed the contents stored at i, it would change it after the call to foo. However, to do that, foo would have to 'dereference' the pointer, like this:

    Code:
    void foo( int *b )
    {
     *b = 7; // the *b means 'what's stored at' b, otherwise known as a dereference.
    }
    On the other hand, the call to foo could work like this

    Code:
    void foo( int &b )
    {
     b = 7;
    }
    Now, if the call were made simply foo( i );, the fact that foo takes a reference means it's passed to the function by it's address, and any change made inside the function changes the value in the calling code - meaning i becomes 7 after the call to foo.

    One of the minor advantages in using references is that since it isn't a pointer, the code using it has no temptation to 'delete' it, or do other 'pointer' oriented things with it. This can avoid bugs in some cases.

  8. #8
    Join Date
    Dec 2006
    Posts
    33

    Re: C++ Pointers

    I personally prefer pointers because I always know when I am directly changing a value external to my function. References obsfucate this. Also, I cannot "reuse" a reference variable name. In short, references are just pointers with a lot of restrictions.

  9. #9
    Join Date
    May 2005
    Location
    Oregon
    Posts
    3,725

    Re: C++ Pointers

    Quote Originally Posted by panzer2k4
    I personally prefer pointers because I always know when I am directly changing a value external to my function. References obsfucate this. Also, I cannot "reuse" a reference variable name. In short, references are just pointers with a lot of restrictions.
    I think you guys Should look on this Link.

    http://www.codeguru.com/forum/showthread.php?t=343473

    Thanx

  10. #10
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: C++ Pointers

    Quote Originally Posted by FAQ
    Q: How are parameters passed to functions?
    A: In C++ there are two ways: by value and by reference

    Q: What about passing by pointer?
    A: There is no such thing; it is a misconception
    If pass by pointer doesn't exist, pass by reference doesn't exist either... There are reference types as there are pointer types, that's all.
    The only real difference between the case of pointers and references is that reference construction is not a simple memove, while, for other builtin types including pointers, memoveis a possible implementation of copy-construction.

    But, in that case, we can say that:
    Code:
    #include <vector>
    
    class MyFunnyClass {
      public:
      std::vector<int> v;
      MyFunnyClass(size_t x):v(n) {}
    };
    
    void func(MyFunnyClass x);
    
    int main() {func(42);} // can we say it's pass by MyFunnyClass?
    That the constructor is not a simple memove operation doesn't mean you have to name this operation differently.

    So, IMHO, either we can say that pass by-whatever-you-like makes sense, in the natural english language, or that all parameters are passed by value (including reference types... even though there is a non-trivial construction).
    I prefer using english, and saying pass by pointer, pass by reference, pass by address.

    Quote Originally Posted by panzer2k4
    I personally prefer pointers because I always know when I am directly changing a value external to my function. References obsfucate this. Also, I cannot "reuse" a reference variable name. In short, references are just pointers with a lot of restrictions.
    *Any* abstraction tool hide things... If you don't like abstraction tools, you shouldn't use typedefs, runtime polymorphism (you don't know which function is called) as well as compile-time polymorphism (overloading and templates), exceptions (you don't explicitly see from here things can be thrown), most of the standard library (with iostreams you don't know what you're manipulating).
    Even C hide things... structures hide offsets of elements (manipulating directly the memory is better), typed variables... They're one of the worst things... You can't know what you're doing inside a function with a statement as simple as a+b, because it depends on the types of a and b.
    B and BCPL are much better on this point, an expression as a precise meaning, outside of any context, since variables are untyped (i.e. they all have the same type)... Well, but even with B, you can't know whether you're using a global variable or a local variable.
    Assembly languages are better!
    But assembly languages are too high level.
    For example, with i386 assembly:

    jmp somewhere

    It's not easy to know exactly which opcode will be used: long jump or short jump?

    Similarly:
    add something, something_else

    There are different opcodes for
    add r/m, imm8
    add r/m, imm32
    add r/m, r
    add r,r/m

    Which is used is not always obvious...
    Worst, with memory operands, it's not obvious whether a SIB byte will be used, especially when the esp register is involved, and displacements... Are they 0, 8 or 32 bits? ebp complicates things...

    No, really, the best language ever is a good hex editor!
    There is no ambiguity... Everything is clear... Everybody can know what's going on, just reading the raw code!

    Quote Originally Posted by Deafboy
    One thing I've always noticed is that it seems you can do the same thing by passing a reference, as if i were to create a pointer. Is there a performance advantage to one or the other?
    In practice, there is no difference, with a dumb compiler, as well as with an optimizing compiler.... And, if ever there is a difference with an optimizing compiler, references will be faster than pointers and probably as fast as const pointers (not pointers to const data).

    Compilers, for performances, are allowed to do whatever they want... If they want, they can add empty loops slowing down the code, if a program contains insufficient comments (to punish the programmer). Of course such compiler wouldn't be very popular.

    A few revelant threads:
    http://www.codeguru.com/forum/showthread.php?t=38331
    http://www.codeguru.com/forum/showth...=383118&page=1
    Last edited by SuperKoko; December 20th, 2006 at 05:41 AM.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  11. #11
    Join Date
    Apr 1999
    Posts
    27,449

    Re: C++ Pointers

    Quote Originally Posted by JVene
    A reference is the same size as a pointer,
    Who says that references are the same size as pointers?

    The ANSI standard doesn't say anything about size of references. As a matter of fact, you cannot take a sizeof(reference_type).

    A reference is just a reference. It isn't a pointer. It's just a "thing" that does "something", and that something is defined by the language. It has no "size" as defined by C++.

    Yes, references are implemented in many compilers as pointers, but nothing stops an implementation from implementing a reference differently, even implementing references to various types differently.

    Regards,

    Paul McKenzie

  12. #12
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: C++ Pointers

    Code:
    template < typename T >
    struct reference_wrapper
    {
       T & ref;
    
       reference_wrapper( T & t ) : ref( t ) {}
    };
    what is sizeof( reference_wrapper< int > ) ? (Presumably implementation specific but you can take sizeof() here).

    If you write a simlar "pointer_wrapper" and take sizeof on it, it may be different to the above.

    (Might be interesting to test on multiple compilers)

  13. #13
    Join Date
    Sep 2005
    Location
    United States
    Posts
    799

    Re: C++ Pointers

    A lot of good points have been made here by the posters above, you should read them over.

    Not much else I can think of to add at the moment.

    All I can say is that when you start to work with non-POD types (meaning classes and objects) and advanced data structures, you will definitely see the value and purpose of using pointers and references.
    Please rate my post if you felt it was helpful

  14. #14
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: C++ Pointers

    Quote Originally Posted by NMTop40
    Code:
    template < typename T >
    struct reference_wrapper
    {
       T & ref;
    
       reference_wrapper( T & t ) : ref( t ) {}
    };
    what is sizeof( reference_wrapper< int > ) ? (Presumably implementation specific but you can take sizeof() here).
    Yes, you can take sizeof() here, but it may be unrelated to the size of a reference (since it's a non-POD type).
    So, sizeof(reference_wrapper) may be smaller than the size of a reference, or bigger than the size of a reference.
    Moreover, a reference is not a POD type, and consequently, is not guaranteed to be stored contiguously (so, for example, memcpy'ing them may not work properly)... They may be internally pointers to structures allocated somewhere when they're constructed and freed when they're destroyed.
    I don't say that implementation doing that make sense (though interpreted implementations are likely to do unexpected things), but, this reference_wrapper doesn't bring any info about references from a standard point of view.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured