1. Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

C++ programming

Discussion in 'Programming & Webmastering' started by Aleksander, Apr 17, 2012.

  1. Aleksander

    Joined:
    Dec 2, 2009
    Messages:
    3,254 (1.93/day)
    Thanks Received:
    304
    Hi all!
    I have been reading a book about C++ and i have a very important question.
    I just finished the chapter of pointers, but i didn't get the idea on
    how to use them, in fact i didnt even make a single program, just kept on reading.
    (I made a lot of programs, but not advanced programs like the ones in the book)
    The question is:
    Keep on reading until i finish the book
    or ||
    Perfect pointers before going any further!

    Also, the chapter was really difficult because it was using pointers with arrays and structs.
    I got the idea of memory allocation though which for the book was most difficult. Any suggestion?

    [Never read a book before with this kind of pleasure :p]
  2. Relinquish New Member

    Joined:
    Jan 10, 2011
    Messages:
    126 (0.10/day)
    Thanks Received:
    15
    Right so lets see if I can help here.

    So a pointer can be considered as a variable but it is one that deals in memory addresses. The whole idea of a pointer is that it points to something in memory by storing its memory location in the actual pointer. Generally a pointer takes about 32bits of memory which is always constant but it can point to anything, which can take up as much memory as possible but the point is that the amount required by a pointer is constant.

    So a pointer may be declared like so:

    Code:
    int *p_myPointer;
    That asterisk indicates that it is a pointer. By placing 'int' before all of this doesn't make the pointer a variable of type int but it helps a pointer greatly. So I've said that it will point to something in memory. However different variables will occupy a different amount of space in memory, but how much memory does a pointer know to look at the target memory address? Well, in this case it knows an int takes up 32bits, which is 4 bytes, so it will look at 4bytes at address X.

    Now, you'll run into many problems if you try to access the above pointer. Why? Because its uninitialized and doesn't have a value. Say I had an int with a value, you can give the pointer its memory address like so (assuming you have already declared it):

    Code:
    int myScore = 50;
    
    p_myPointer = &myScore;
    That and symbol used is the 'address of' operator and it takes the address of a variable or object and stores it in a pointer. Now that the pointer has the memory address of myScore, it can not only access and see its value but it can also change it like so:

    Code:
    //Print to console
    cout << "My score is: " << *p_myPointer << endl;
    
    //Change value
    *p_myPointer = 10;
    
    //Reprint value
    cout << "My score now is: " << *p_myPointer << endl;
    What the asterisk does after you declare a pointer and you use it in the way I did is that is show the value pointed to by a pointer. So it shows what is stored at the memory address X. Equally this can be used to reassign values, like I did. This is known as dereferencing.

    Now you can also create pointers that don't take a memory address specifically from another variable/object, but that creates variables that are the same type that the pointer points to using dynamic memory. They perform the same as an ordinary variable/object but the syntax for doing things may be different (like using the derefrerencing opperator). E.g:

    Code:
    int *p_aNewPtr = new int;
    Whats happening is that you're declaring a variable that points to an int and using new to allocate enough memory for an int. Now you can go and give it a value:

    Code:
    *p_aNewPtr = 690;
    If you perhaps have an array of an undetermined size when your program starts you can create one based on a variable like so:


    Code:
    int *p_aNewPtr = new int[arraySize];
    Assuming arraySize is already declared. What was created above was a pointer to an array and the pointer gets the address of the first element. You can use the dereference operator to make life difficult but an easier way to access all the elements is to use the subscripting operator, much like the way you'd normally access an array:

    Code:
    p_aNewPtr[0] = 3;
    When dynamically allocating memory from the heap, please remember to give the memory back when you're finished with it using the delete operator. There are two ways: for a variable and for an array like so:

    Code:
    delete p_aNewPtr;
    or
    Code:
    delete [] p_aNewPtr;
    I hope this has helped.
    Aleksander and Jizzler say thanks.
  3. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Stop and learn pointers. It is key to understanding C++ code as they are used all of the time.
  4. Maelstrom

    Joined:
    Sep 10, 2008
    Messages:
    534 (0.25/day)
    Thanks Received:
    159
    Location:
    VA/PA
    This x1000000. They're incredibly important and powerful.
  5. Aleksander

    Joined:
    Dec 2, 2009
    Messages:
    3,254 (1.93/day)
    Thanks Received:
    304
    WOW
    Thanks relinquish :)
    Looks like i will have to learn them a lot.

    Also, there are the struct pointers which made me a bit of unbalanced!
    like:
    Code:
    pt->name="Adam";
    
    Edit: why they are so useful? I mean except memory savings?
    Last edited: Apr 18, 2012
  6. AphexDreamer

    AphexDreamer

    Joined:
    Jun 17, 2007
    Messages:
    7,078 (2.74/day)
    Thanks Received:
    912
    Location:
    C:\Program Files (x86)\Aphexdreamer\
    From what I learned in my Intro Class, perhaps this will be a simpler to the point example for ya.

    Lets say you have

    Code:
    int aa = 7; 
    //initializes aa to 7
    
    int *aaPointer = &aa; 
    Makes a pointer called aaPointer that points to the address of int aa which when called could be something like 0029F989. The asterix is key to declaring the variable as a pointer. Without it you couldn't direct it to the address of aa which is what & does.
    ------------------------------------
    Now if you were to do

    Code:
    cout<<aaPointer; //You get the addres like 0029F989
    but if you do

    Code:
    cout<<*aaPointer;
    The astrix in this case dereferences the variable aaPointer from the address it was set to point at to what is inside the address, the value 7.

    I'll add my classes PowerPoint on it for ya.

    Here it is: http://www.slideshare.net/gerfeso/unit-6-pointers
    Last edited: Apr 18, 2012
  7. Yukikaze

    Yukikaze

    Joined:
    Sep 24, 2008
    Messages:
    2,309 (1.09/day)
    Thanks Received:
    481
    You gotta figure out pointers, as they are an integral part for C/Cpp programming. If you need some specific help, drop me a PM with specific questions and I'll do my best to answer.
  8. Relinquish New Member

    Joined:
    Jan 10, 2011
    Messages:
    126 (0.10/day)
    Thanks Received:
    15
    I was a little tired last night when I wrote what I did, so I forgot to talk about structures. I also wasn't sure what you were unsure about but I think I can help now.

    So the way I learnt what a structure was, it was that its like a way for a programmer to create their own variable type made up of the existing built in variable types and or possibly user defined objects and even other structures. So we may create a high score structure like so:

    Code:
    struct highScore
    {
    string name;
    int score;
    };
    
    These are some of the things associated with a high score. Now if I declare a variable of type struct for a player that may use our program, we would do this:

    Code:
    highScore player1;
    
    Now at this point, lets say we have his or her's score and name, how do we change the variables in the structure? Well those variables are known as fields and to access the fields we would use the period key like so:

    Code:
    player1.name = "Aleksander Dishnica";
    player1.score = 500;
    Now for a pointer to a struct. We know that a pointer will have a memory address stored in it so what we can't just do is this:

    Code:
    highScore *p_player1 = new highScore;
    
    p_player1.name = "Aleksander Dishnica";
    
    You will get a compiler error if you use a period key with an asterisk. What you need to do is get the object that the pointer is pointing to by dereferencing it and then access the fields by using the period key like:


    Code:
    (*p_player1).name = "Aleksander Dishnica";
    
    There is one more elegant way of doing the last step and that is by doing this:
    Code:
    p_player1->name = "Aleksander Dishnica";
    
    The '->' operator dereferences and accesses the fields of a structure or a class.

    So to answer your last question. Pointers are important because they are fast! Especially as arguments to a function.
    Aleksander says thanks.
  9. Maelstrom

    Joined:
    Sep 10, 2008
    Messages:
    534 (0.25/day)
    Thanks Received:
    159
    Location:
    VA/PA
    Dynamic memory. I've use for linked lists and binary trees, among other things. I'm sure some of the more advanced/experienced c++ programmers here could give you more reasons.
  10. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Pointers are important for passing variable into methods (function) by reference instead of by value.
    Since Relinquish is doing such a fine job with example, and I just got out of bed and my caffiene levels are low, I'll let him put up an example so it's correct. :D
  11. Aleksander

    Joined:
    Dec 2, 2009
    Messages:
    3,254 (1.93/day)
    Thanks Received:
    304
    LOL!
    I was wondering... pointers are the same with java too?
    Or even same with all other languages that have pointers?
    Or not?
  12. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    The concept of pointers is the same in all languages. Their syntax, implementation and restrictions can vary depending upon the language.

    How's that for being crystal clear! :laugh:
    Aleksander and Jizzler say thanks.
  13. stupido

    Joined:
    Sep 23, 2009
    Messages:
    150 (0.09/day)
    Thanks Received:
    21
    Location:
    Belgium
    master the pointers and you'll master the c/c++ programming, my young padowan... :cool:
  14. Vinska

    Vinska

    Joined:
    Jul 23, 2011
    Messages:
    1,381 (1.27/day)
    Thanks Received:
    1,187
    Location:
    Kaunas, Lithuania
    From my own experience, I can say that the best way to learn using pointers is... to use pointers. Practice. Practice. Practice.
    In other words - unlike many other topics, just reading about pointers doesn't help that much in learning them. To truly master pointers, use them in practice. While using them, try to think up and see as many possible uses for them as possible - as there are lots. Some that would probably never come to mind when using them just a little, let alone from simply reading a textbook.
    Pointers are a darn powerful and useful "breed of beasts", as long as their "trainer" knows how to "train these beasts to perform exquisite tricks".

    And now on the more humorous side:
    Pointers can help do a lot of things. Like: making a program run faster, make some forms of code easier to write, produce segfaults, reduce memory usage, segfaults, code obfuscation, working with bare hardware, segfaults, memory manipulation, did I mention segfaults? Yes, also helps to make segfaults, just to make one's day happier! Weee!
    (can't help not to also point out: This ^____^ )

    Edit: And: Yeah, what stupido said... =3
    Last edited: Apr 26, 2012
    Aleksander and Jizzler say thanks.
    Crunching for Team TPU
  15. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Here's a ittle to chew on Alek ...

    There are three basic ways to pass arguments to functions. By value, by reference and by address.

    When you pass an argument by value, a copy is created within the scope of the function and destroyed when the function terminates.
    Code:
    void foo (int a)
    {
        a++;
        cout << a << endl;
    }
    
    int x = 1;
    
    cout << x << endl;
    foo(x);
    cout << x << endl;
    
    cout results...
    x = 1
    a = 2
    x = 1
    
    When you pass an argument by reference ...
    Code:
    void foo (int &a)
    {
        a++;
        cout << a << endl;
    }
    
    int x = 1;
    
    cout << x << endl;
    foo(x);
    cout << x << endl;
    
    cout results ...
    x = 1
    a = 2
    x = 2
    
    Passing an argument by address ...
    Code:
    void foo (int *a)
    {
        *a = 2;
    }
    
    int x = 1;
    cout << x << endl;
    foo (&x)
    cout << x << endl;
    
    cout results ...
    x = 1
    x = 2
    
    This is just basic pointer stuff. It gets a lot more complicated. :D


    @Vinska : You forgot to mention segfaults. lol
    Last edited: Apr 18, 2012
    Aleksander and Relinquish say thanks.
  16. Relinquish New Member

    Joined:
    Jan 10, 2011
    Messages:
    126 (0.10/day)
    Thanks Received:
    15
    Well I was trying, but I couldn't give a better example. The last section of code that I highlighted above is quite significant, even though it might not look it.

    Let me explain. If you pass by value, you are copying the contents of a variable to a temporary copy within a function. Depending on the size of that variable it can be a lengthy process. So something that's 24 bytes will take longer to copy than something that's 4 bytes. 4 bytes is quite small so when you pass by address using pointers, its quite quick.

    So when I say significant, I mean it in terms of performance.

    All I will say about pointers is don't get carried away with them. You can end up with some nasty memory leaks. Like someone else said, practice and practice and see when it is necessary to use them.
    Kreij says thanks.
  17. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Relinq is right, it can be extrememly significant in terms of memory use (stack) and performance.

    Here's an extreme (but pretty useless) example ...
    Code:
    
    struct MyStruct
    {
        int a;
        int b[1000000];
    } myStruct;
    
    void foo(MyStruct z, int b)
    {
        z.a = b;
    }
    
    foo (myStruct, 2);
    
    You just created a copy of MyStruct which includes the million int array in order to just change the value of its "a" field.

    Code:
    void foo (Mystruct *z, int b)
    {
        z->a = b;
    }
    
    foo (&myStruct, 2);
    
    This time you just sent the address of MyStruct to modify the field.

    (I think I got the syntax right. lol This is why I use C#. It makes my brain hurt less)
    Last edited: Apr 18, 2012
  18. Vinska

    Vinska

    Joined:
    Jul 23, 2011
    Messages:
    1,381 (1.27/day)
    Thanks Received:
    1,187
    Location:
    Kaunas, Lithuania
    There is also one more LARGE difference:

    In the first example, after changing the field a, the change "stays" in the function - after the function finishes its execution, the said copy goes out of scope and is destroyed, leaving the value in the original copy that was passed to the function, unchanged.

    In the second one, since the function is then working with the "original" copy, any modifications stay. This is very useful, when one needs that a function would "permanently" modify a variable passed to it.

    P.S. Kreij, there was a small mistake in Your first example, so I edited it in the quote. I hope You don't mind.
    P.P.S Also, Kreij, I think there also is a mistake in Your second example. I also edited this one in the quite.
    Last edited: Apr 26, 2012
    Kreij says thanks.
    Crunching for Team TPU
  19. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Thanks Vinska! more than once I've beat my head against a wall trying to figure out someone else's post of code only to find they had made a error when typing. lol
    Changed in my original post also.

    I wans't sure about that, Vin. Dont' we need to access the derefenced pointer inside the function also?
    (Like in post #15, example 3)

    @Alek : Did your head explode yet? If not we can start on pointers to pointer, null pointers, void pointers and that kind of stuff. ;)
  20. Yukikaze

    Yukikaze

    Joined:
    Sep 24, 2008
    Messages:
    2,309 (1.09/day)
    Thanks Received:
    481
    Pointers to functions anyone ? :D

    Oh, and there is one thing to always remember regarding memory leaks (if you're on *nix):
    "Be kind: Valgrind."
  21. Vinska

    Vinska

    Joined:
    Jul 23, 2011
    Messages:
    1,381 (1.27/day)
    Thanks Received:
    1,187
    Location:
    Kaunas, Lithuania
    We do need. But -> is a dereference operator. So, also adding a * would make it to try dereferencing an address that is the value of a. That would probably need a typecast, though. Yet, not what we need that in this case anyway.
    ...I got sidetracked, didn't I?

    Also, to quote cplusplus.com (quote slightly modified) :
    Last edited: Apr 26, 2012
    Crunching for Team TPU
  22. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Okay you win. I'm getting page faults when trying to access C++ info in my brain.
    I'm going back to my C# GPU-Z shared memory thread. :D
    Last edited: Apr 18, 2012
  23. Aleksander

    Joined:
    Dec 2, 2009
    Messages:
    3,254 (1.93/day)
    Thanks Received:
    304
    I don't know what to say!
    I can't thank you guys enough for your help :)
  24. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.11/day)
    Thanks Received:
    5,615
    Location:
    Cheeseland (Wisconsin, USA)
    Just say you won't give up and will keep letting us help you. :toast:
    Someday you will understand that passing the knowledge you have gained to someone who is new at it, is more important and gratifying than using it.
    Aquinus, Vinska and Aleksander say thanks.
  25. Aquinus

    Aquinus Resident Wat-man

    Joined:
    Jan 28, 2012
    Messages:
    5,891 (6.56/day)
    Thanks Received:
    1,888
    Location:
    Concord, NH
    That is the name of the game, my friend. All the code I write, I license GPL v3 and that is part of the reason. It's pretty cool give the world something you made and see other people make it better. I'm all for free software and the open sharing of knowledge.

    http://www.gnu.org/philosophy/free-sw.html

    *: Best statement in the entire document.
    Vinska says thanks.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page