r/AskComputerScience • u/hub_batch • Sep 24 '19
What is the point of pointers in C++?
Sorry if this belongs in a programming based sub- I couldn't find one that was Q&A specific that was super active.
Right now we're learning about pointers in my C++ class. I don't understand why. What's the "point" of using a pointer? Why don't we just continue to use variables/access variables(or arrays, structs, etc) directly?
I know this is probably a little basic, but my teacher has dodged the question (a little out of scope for the class apparently).
3
u/WiggWamm Sep 24 '19
This used to confuse me too. Basically, all of he core languages use pointers, but some of them hide it from you (Python, Java, C#, etc). C and C++ don’t. You have to use them.
This allows you to get better performance. Think of it like a car. If you have an automatic transmission, the car shifts gears for you and does that work for you. In a manual transmission, you have to shift the gears. It’s more work and more confusing, but you can get better performance from a manual if you use it right.
The same is true for languages like C++. You can get better performance because you get to use the pointers, so you get to control the overhead of the program and garbage collection.
Does that make sense or answer your question? Or were you asking more about what a pointer is? I can try to help you with that too if you’d like.
4
u/hub_batch Sep 24 '19
This actually answers it perfectly. I'm experienced in languages like C#, so I was wondering why I never really learned about pointers in C#. Makes sense that theyre just hidden; so, I didn't understand why we were learning them in C++ if languages like C# don't even "have" them. They do, just hidden.
Thanks so much!
2
u/deelowe Sep 24 '19
This is why students in compsci should be introduced to hardware and assembly early in their studies. You can't do anything on a PC without allocating and manipulating memory. This is core to literally every operation. It's everything.
1
u/hub_batch Sep 25 '19
I am in that class right now, lol. I am early in my studies. I understood that we allocate and manipulate memory but didn't understand why you couldn't do this just with a variable and had to use the pointer.
2
Sep 24 '19
I think this is a great answer and I'm super enthused it was here, but there's one minor point I'd like to add:
Any time you're in a language that hasn't got pointers you can see (java, C#, python), there's another program sitting under it (the JVM for java, the python interpreter for python) that does use pointers extensively, as the above poster said. Whatever this is, it is itself a program, written in a language that does have pointers like C or C++ (or maybe Rust or something nowadays), that is handling all of the pointer details and memory-management details for you.
If you drill down to fundamentals, your operating system, its memory manager, etc, are all in languages that use pointers extensively because you need pointers to directly handle memory and addresses for memory. So those programs are written in a language with pointers, which in turn gets compiled into assembly for which pointers (memory addresses) are one of the basic building blocks.
Pointers are a source of a *lot* of *major* glitches, exploits, etc; they're easy to screw up, dangerous to use, and inconvenient. (See: Buffer overflow). So it's by design that they're "hidden" from you in a lot of modern languages, so that you don't have to deal with them and there's no risk of a pointer-related glitch destroying your program or making it insecure.
It's ... odd to me that a teacher would avoid this topic while teaching C++. C and C++ are more difficult to code in than a lot of other modern languages. They are still used largely because they have pointers, not in spite of it. Pointers let you do things you literally can't do in languages that don't offer direct memory access, apart from C++ just being faster. So, pointers are fundamental to the purpose of the language and to computer science generally.
1
u/hub_batch Sep 25 '19
I think he's avoiding it because not everyone in the course is a CS major, or this is the last programming course they'll take. For me, its far from it, since I'm in the SE program instead. But that's few and far-between. Or maybe he plans to cover it later and I'm jumping the gun. Either way, thank you for your input! In another course I'm learning about how data and memory allocation works at the low level, but I never really made the connection between them. This has helped!
2
u/IAmNotNathaniel Sep 24 '19
Think about functions that "pass by value" vs "pass by reference"
What are you passing, exactly, when you are passing by reference?
Depending on the language, it's basically just a pointer to the variable's memory. You just can't always get to that reference directly, as it's automatically de-referenced inside the function.
2
u/qznc Sep 24 '19
C# has pointers. They even look like in C/C++. It is only allowed in unsafe though.
1
1
u/WiggWamm Sep 24 '19
No worries haha. I had the same confusion too when I first started. Good luck!
1
u/deelowe Sep 24 '19
Pointers are just memory manipulation. I'd argue that any code running a Von Neumann architecture would be using some form of them (perhaps via assembly instead of c, but still).
1
u/qznc Sep 24 '19
One might argue that assembly does not have pointers, only words.
1
u/deelowe Sep 24 '19
x86 assembly has pointers (e.g. mov [...], ... or mov ..., [...])
1
u/qznc Sep 24 '19
It is a rather philosophical question.
There are only words stored in registers. You can treat them a addresses and access the corresponding memory. You can treat them as integers and do arithmetic. You can treat them as floating point numbers and do arithmetic. You can also treat them in various other ways.
int x = 42; int *y = &x; size_t z = (size_t) y;Everybody would agree that y is a pointer. Is z a pointer? It contains the same value as y.
What makes a value a pointer in C is its type. If only the type makes a pointer and assembly is untyped, then there are no pointers in assembly.
1
u/deelowe Sep 24 '19
I was commenting that syntactically, x86 assembly has commands for storing and dereferencing memory locations. It works the same as in C.
1
u/qznc Sep 24 '19
I know. I'm just musing if that means it has "pointers".
However, you have to be somewhat careful about pointers in C. It is really easy to encounter undefined behavior and then it might behave in rather interesting ways. For example, subtract two pointers (aka memory locations) from each other. Assembly will always treat them as integers. In C it depends on the pointer type. The result is different when you use int* vs char*. Well, actually it is undefined behavior and the compiler could turn it into anything.
Thus I disagree that "It works the same as in C."
1
u/deelowe Sep 24 '19
Yeah, practically things are very different language to language. A pointer is really just a theoretical construct anyways. The real discussion is around what languages allow you to directly interact with memory addresses and the contents thereof. In that respect, ASM is obviously more complete than C.
2
u/elperroborrachotoo Sep 24 '19
It is one of the topics that will become clear later. Your future self will thank your today's self when for listening when you come to data structures.
Questions: write a program that reads numbers from a file, and then outputs them in reverse order. The number of values in the file is not known in advance. How do you implement this?
... using as little memory as possible
How do you represent a graph like this, where the user can add vertices and edges?
Note that in a modern C++ course, pointers wouldn't be taught that early. Looks like your course material - or teacher - is stuck in the nineties, when this was necessary. It's OK, it's just the hard way to learn.
2
u/hub_batch Sep 25 '19
I'm actually in the "intermediate" course, so this is like C++ Part Two, lol. I have a lot of fundementals down at this point so we're gettung into the nitty gritty stuff right now.
6
u/PC__LOAD__LETTER Sep 24 '19 edited Sep 24 '19
It’s like if you wanted to let your neighbor borrow your car. Would you buy a whole new car just for them to use for a day and then throw away, or would you give them a little note that says “hey chief, it’s right out there in the driveway, house #986”.
In a program, you might have a giant class object that you allocated on the stack. You want to pass that into a function to do something with it.
It would be incredibly inefficient to pass an entire extra copy of that object into the function with another big stack allocation.
The solution? Pass a pointer to that object. Just like passing a note with your car’s location to your neighbor instead of giving them a copy of your car.
Sure, you could say “but languages should be smart enough to know that I don’t want to pass a copy, I just want to pass a reference”, and, hey, you’ve just invented higher level languages!
The tricky bit is that, in some types of programming, and some types of programs, there isn’t a high level language that’s going to be general enough to be useful and also specific enough to do exactly what you want all at once.
C-like languages are “low level” because they don’t abstract that control away from the programmer. Pointers let you have explicit control over how you’re manipulating memory by just passing a memory address (usually a “typed” memory address, like MyBigObject *mbo) instead of copies or implicit references.
There are certainly more to high/low level languages than just pointers, but the concept of sacrificing performance for convenience and ease of expression and development speed (i.e. writing “sort” in one line rather than a few hundred lines of assembly) is basically at the root of it. They’re different tools for different jobs.
10
u/khedoros Sep 24 '19
I couldn't find one that was Q&A specific that was super active.
r/cpp_questions isn't huge, but it's pretty active.
Anyhow, these come to mind (there are more applicable situations, but it's late).
You want to be able to pass large objects into functions without actually copying them in (they'd have to be passed by pointer or reference)
You want to modify a variable that isn't in your current stack frame
At the core, any dynamic memory allocation will use pointers, even if it's actually hidden by the interface that the class provides. Mostly only fairly simple programs know how much memory they'll need ahead of time.
5
u/detachmode_com Sep 24 '19 edited Sep 24 '19
Pointers are a core concepts of how computers work.
For example, every computer executes a program by storing the address of the current executed line inside a registry in processor (aka program counter) and increases it by one after finishing the current instruction set. Or in case of a jump or move instruction (aka if statement / loops ) it changes the program counter to some value defined by the program itself.
Storing a memory address and being able to do math with it is therefore a core feature to write programs.
Since C++ is very low level (close too assembly code) it makes sense it has this feature.
13
u/oligIsWorking Sep 24 '19
WTF is wrong with your teacher.
If they are teaching pointers your question is not out of scope, your question shows that you havent fully grasped the concept and should be an indicator to them to try and enforce the concepts.
2
u/SirMarbles Sep 24 '19
Professors are dipshits. My prof literally doesn’t teach code, but makes are assignments code based. Da fuq. Then I spend forever trying to teach myself how to do something.
2
Sep 24 '19
[removed] — view removed comment
2
u/SirMarbles Sep 24 '19
My engineer class in hs consisted of building and designing popsicle bridges and the sort
0
u/elperroborrachotoo Sep 24 '19
Typical c++ course of the nineties. How dare you use a linked list before you can implement one?
2
2
u/landpet Sep 25 '19
Pointers are very useful for a number of reasons. They basically are pointing to a specific address. This makes them super convenient and fast to pass to other functions to modify. If you modify the value in that address, it's updated everywhere.
Example, if you had a 1000 element array and you wanted to print the elements in another function, without using it's address to pass it, you would literally make another copy of it just to pass it to another function. Not to mention the memory hit, this would also be a slow process. Compared to just passing an address of the array.
Linked list are another great example, you can literally remove, add elements just by updating the pointers.
-5
-12
39
u/thegreatunclean Sep 24 '19
Pointers are just a method to refer to data somewhere else. That's it. It's a pretty fundamental ability of the language.
Because very often you don't actually want complete instances of the thing you're storing in-line in the structure.
Think of a linked list. Manipulating elements in the list is trivial because you're just changing pointers to data that is held somewhere else. Removing an element is as simple as changing a few pointers.
Compare that with an array. If you want to remove an element you have to somehow shift all the following elements down, and that may be far from simple. Many types cannot be trivially copied and require expensive move operations; C++ has options to make this process less painful but it's far from free.
It's hard to overstate just how important pointers are to C++, even if much of the usage is hidden from you. I can't think of a single data structure that doesn't use them everywhere.
Take a day and try to implement your own
stringclass, following thestd::stringAPI as close as you can. Orvector. That may help internalize just how useful pointers can be.