Pointer and Dereference clarification and advice

I need some help in clarifying some points about pointers. In the example below is a short program, and a description of what each line does. Am I understanding this correctly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main ()
{
    int octo = 8;
    cout << &octo << endl;

    int *octo_pointer;
    octo_pointer = &octo;
    cout << octo_pointer << endl;
    cout << *octo_pointer << endl;

    return 0;
}


Line 7 - Create an int variable called octo and assign the value of 8.
Line 8 - Print out the memory address of where the variable octo is stored at.
Line 10 - Create a special int variable, a pointer, called octo_pointer.
Line 11 - Assign the pointer the memory address of the variable octo.
Line 12 - Print out the memory address of the variable the pointer is pointing to. The result should be the same as Line 8.
Line 13 - Print out the value that is stored in the address where the pointer is pointing to.

I know for very large programs using pointers saves time/space/other things, but what about for small or medium-sized programs? At what point in a program do you think, okay, this program is getting pretty big, time to start using pointers?

Now anytime I need to pass the value of a variable between functions I just use the dereference operator (int &current_health) or whatever, and it works fine.

It is feasible to go 100% dereference and 0% pointers? Or how feasible is it?

Thanks

Also, is the Preview glitched. Never seems to work for me.
you seem to have understood all the lines correctly.

pointers are almost requires for a variety of algorithms. For example, you can collapse a linked list into a vector, but its ugly and you are really just subbing array index for pointer. They save a lot of copying and data movement -- for example, a huge class with 1000s of bytes of data, you can sort it by just sorting pointers to the objects, without having to swap all that data over and over.

save yourself a headache now. References are pointers. Syntax aside, its the same thing.

void foo (int *a)
void bar (int &a)
...
foo(&a)
bar(a)
slightly different, but both of them use a pointer to the object rather than a copy of the object. and conceptually do pretty much the same things (details aside for a moment, we are at the concept level)

its possible to write without pointers, but don't fear or avoid them. Again, they are necessary for a ton of purposes. Most complex algorithms and data structures will perform better, be easier to write, and make more sense with pointers.

pointers let you allocate like an array, and a reference cannot do that unless its a reference to an actual array. Which brings up that array names are also pointers, conceptually. These items alone will have you needing a pointer sooner or later.

Last edited on
The size of the program doesn't matter. There are things you can do with pointers that can't be done without them, regardless of how complex or simple the program is.

Now anytime I need to pass the value of a variable between functions I just use the dereference operator (int &current_health) or whatever, and it works fine.
The & in that context is not an operator, it's a syntactic element that means the thing being declared is a reference.
The dereference operator, incidentally, is * when used in a unary context.

It is feasible to go 100% dereference and 0% pointers?
No. Pointers do things that references can't, and references have guarantees that pointers don't.

The preview for new threads may be broken. The preview for normal posts works fine.
Thanks for you suggestions guys.

In my mind it's just super-easy to reference everything (int& something) where I need the actual value and pass that between functions.

On the other hand, pointers are more complex and was hoping to avoid them. I'll just slowly study them at my own pace then, and eventually I'll learn when and how to incorporate those into my games. I mean programs.

Thanks again.
@volTron

There was a topic recently which talked about how to teach C++ (Stop teaching C language)
http://www.cplusplus.com/forum/lounge/211316/

Learning about pointers is something that can be delayed for quite awhile. As helios says, there are situations where either pointers or references are appropriate.

One can do an awesome amount of things by just using the STL (Standard Template Library) and references. Start with STL containers like std::vector and STL classes like std::string, using their associated functions. Also look at the STL algorithms.

That way you can often do what is called value semantics (pass things by value) basically without any penalty. I don't want to be seen to being dogmatic about that - there are lots of details about how things are copied / elided / moved etc. Make use of references to avoid copying entire objects. For example:

1
2
3
4
5
6
7
8
void MyFunction(std::string TheString); // function declaration
 // ....
std::string Name = "Fred Astaire";
 MyFunction(Name); //function call, pass by value
 // function defintion
void MyFunction(const std::string& TheString) { // accepted as pass by const reference
    std::cout << "The string is " << TheString << "\n";
}


One often doesn't need to create references directly, just make the function parameter a reference like I did.

Btw, it's not worth it to do references for basic types like int or double, unless you want to change the value in the outer scope. This is because the reference takes up the same amount of memory (or more) than the original type, so one may as well pass by value.

Good Luck !!
You just gave me a lot more stuff to chew on. Thanks. Learning more about pointers I'll try to delay. At least for now. I have the basics down, but I think it gets more complex.

I'll be reading your link next.

Thanks again.
The other thing is that teachers are usually at cross purposes with that learning strategy. They want to give a well rounded education, so they get their students to, for example, write their own sort routines or data structure. This is so they understand how they all work, as opposed to just using the STL stuff, which is too easy. So what happens: the student has to write their own linked list; Bang! they immediately have to learn pointers !!
again, pointers are not all that scary. Its a pretty simple syntax, and a pretty simple concept, once you "get" it.

imagine memory of your pc, the ram, is just a big array.
a pointer is conceptually just the array index to that. The index isn't the data, its where the data is.

It does not get much more complex than that. Learn new, delete, &, *, [], null/nullptr syntax, which is a couple of keywords and a couple of operators, and you will be more than 3/4 the way there. Then its just applying it, which comes with practice and time.

I absolutely hate linked lists (a lot of clunky code to invent a slower than everything else container), but write one, and youll learn all you need to know in short order :)
jonnin wrote:
Learn new, delete, ....


So the beginner is writing a linked list, they need pointers. But new and delete should specifically be in the realm of library writers. The problem is that a beginner uses them and thinks that they are OK, so then uses them all the time. Often they are only using them purely because they return a pointer, never mind any concept of it being placed on the heap, or any knowledge of what heap and stack are. Much better to learn smart pointers like std::unique_ptr instead of new / delete. The biggest problem with new is if something throws an exception, the delete is never reached, so there is a memory leak. Smart pointers avoid that problem, so that's why one should learn them.

But I agree pointers are not that scary. They are just a variable that can hold a memory address, and there are only a few different ways one can operate with them. The problem lies in when a budding C++ coder descends into the realm of C programming and starts doing pointer arithmetic and such. If one wants to learn C, then treat that as a separate subject altogether.
I challenge you to implement a linked list with smart pointers. Perhaps that'll show you the uselessness of that endeavor.
@helios

I shouldn't have put all those ideas into one paragraph: it's misleading to imply that the first idea leads to the last idea.

It's not just me saying this, see what is discussed here:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines.html#S-resource

The part about new / delete:

CppCoreGuidlines wrote:
R.11: Avoid calling new and delete explicitly
Reason

The pointer returned by new should belong to a resource handle (that can call delete). If the pointer returned by new is assigned to a plain/naked pointer, the object can be leaked.
I challenge you to implement a linked list with smart pointers

yeah, around last christmas cire and mbozzi taught me the (humbling!) lesson that smart pointers and linked lists don't actually go well together
therefore i was surprised to find this peer reviewed article recently:
https://thesai.org/Downloads/Volume6No2/Paper_29-Implementation_of_ADS_Linked_List_Via_Smart.pdf
but when i tried to work the authors' code into a small (unsaved) test program it still seemed to leak
new and delete are c++ my friend.

C uses malloc and free.

And just because someone on the web said it and it can be linked to does not make it ideal for everything. This fear of making a mistake is for java programmers. Every time some nimrod says to avoid doing something because it could be done incorrectly, I cringe a little inside.
Last edited on
My point about linked lists was that a beginner successfully implements them using new and delete, then start using them for everything.

One can do an awful lot by simply using an STL container.

The part I quoted from Cpp Core Guidelines was just 1 paragraph - one should read the entire chapter. Cpp Core Guidelines is written by Stroustrup & Herb Sutter.

IIRC, Herb Sutter said somewhere that in 2003, they said to everyone use new and delete, then from C++11 onwards they said to use smart pointers instead.

Also I have never rarely seen expert coders like JLBorges use new, and read this post by Cubbi

http://www.cplusplus.com/forum/general/179117/#msg881021

Here's one from JLBorges:
http://www.cplusplus.com/forum/beginner/154004/#msg796734

A work around for make_unique !!
Last edited on
Shit! I wrote this hours ago and completely forgot to hit "submit". Now it's a bit less relevant:

(To TheIdeasMan)
I don't follow. Are you saying that you agree with me or not?

There's no point in implementing a linked list with smart pointers. In the worst case you end up creating unreleasable reference cycles (in the case of a doubly linked list), and in the best you end up manually releasing each pointer anyway to avoid a stack overflow.


My point about linked lists was that a beginner successfully implements them using new and delete, then start using them for everything.
Fair enough, but that's an argument against poor teaching, not against implementing common data structures for educational purposes.

One can do an awful lot by simply using an STL container.
You can't learn how to implement a linked list without actually doing it.

gunnerfunner: It can be done, but it's an exercise in futility because, as I said above, to prevent leaks from reference cycles, and stack overflows when releasing long lists you have to do same work you'd do with raw pointers. You have to unravel the list node-by-node and explicitly release each node at destruction, whether you're using raw pointers or smart pointers.
Last edited on
Hi volTron

have you heard about smart pointer? :D

if not this is what I have found recently, quite a nice article.

https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp

in summary pointers are great but they can be dangerous as people forget to free memory that pointer is holding.
:)
Topic archived. No new replies allowed.