A question about pointers

I am new to C++. However not to programming itself, as I have decent proficiency with C# & Visual Basic (unfortunately WINDOWS-only languages). Yet now I have gained a love for Linux as my OS, and as such i would like to be able to program applications and games for my OS of choice. However, the complexity of C++ is far beyond C# (which i think should adapt another name because it is far removed, in my opinion, from the C & C++ languages, perhaps they should just name C# MS.Net.... )

Anyway, I'm currently teaching myself C++ from a collection of books... and the one thing i have trouble wrapping my head around is pointers (every other concept i have understood without any problems whatsoever).

Reason #1: First thing that baffles me is the necessity of them. I don't see them being necessary. Almost all of the books fail to give me any practical need for them to exist, Their best explanation is "to access and manipulate values outside the current scope. However, every use i've seen of pointers could be replaced with a variable...

Now one book that i'm using, as i arrive at each new concept in C++ gives "real-life" examples of the necessity of the concept, which makes it easier to grasp WHY this concept is a integral part of C++. I like that about this book, and it is my PRIMARY source of learning C++. So finally i arrive at pointers (and having been baffled about this concept and its necessity from every other C++ book I've ever read, I looked forward to a "real-life" comparison of the integral use of pointers, to better understand a situation when a pointer is a better way to access values than a variable. Guess what, suddenly the book decides this will be the ONE subject that they will approach antiseptically, with absolutely no attempt to be informal about it.


Reason #2: Every book I'm read to expand my knowledge of C++ has suggested that pointers can be dangerous to use. So why use them. If you are trying to retrieve or manipulate a value in memory why not use variables in all cases? Ok so a pointer actually addresses the space in memory that contains the item that a variable represents... in cases where one would need that address, to manipulate WHERE in memory the info is stored i can understand using pointers... but for simply manipulating data stored in memory... I'm left with no understanding of why pointers need to be able to do this.

So if i have a variable that points to data in memory, a pointer that points to that address in memory, its a bit baffling to me why i don't just use the variable to access and manipulate the data in the variable.

In writing this i actually come to see how it could be useful to know where the box that you stored your favorite coat in, once winter comes around is helpful. But I still don't think i get it. To me a pointer seems like something used to find something that something else has already found... or maybe a pointer is like a piece of paper that i've written down the location of the box i've put my favorite coat in and the variable is label on the box? But if that's the case, couldn't i just pass the label of the box as a reference to a function that is designed to tell me the location of the box, instead of trying to remember what piece of paper i wrote the location of the box down on?


Yeah i know that whole thing above might be convoluted.... but so is my understanding of pointers...

I have continued on past pointers with learning C++ but i feel as though i am missing out on something by not COMPLETELY understanding their contribution to C++.

Can anyone clarify this for me?




Last edited on
First thing that baffles me is the necessity of them. I don't see them being necessary.

Actually they are incredibly necessary (they are involved in the implementation of virtual functions, references, member functions, iterators etc, etc). The question, perhaps, is whether they are necessary for a programmer to manipulate. Lets think about what our data objects can be when we are in a particular function (ignoring static and global variables):

1. A variable on the stack. In this case it is either a local variable or a variable that has been passed by value. We cannot program successfully with only local variables, and when we pass a variable by value, what we do is actually make a copy of the entire variable. This can be very inefficient.

2. A reference to a variable, probably because the variable has been passed by reference to the function. This is much more efficient, because we do not copy the entire variable. But references are implemented in terms of pointers. They simply have less functionality (you cannot change the address pointed to by a reference, nor can a reference be null, etc).

3. A pointer to a variable. This is much the same as having a reference to a variable, but we are now explicitly manipulating the address of the variable as an address, rather than a pretend variable. There are reasons to do this - there may be situations where there is nothing pointed to by the pointer (ie we have a NULL pointer), but references always, well, refer! Or we may wish to be able to change the object pointed to, which we cannot do with a reference. Or we wish to engage in pointer arithmetic. And this is not an exhaustive list :)

Cheers,

EA
Last edited on

The question, perhaps, is whether they are necessary for a programmer to manipulate.


I wish i could have been more clear in saying that was my question.

I appreciate the response, and I'm glad i understand now how/when/why of pointers... you were very helpful.

I guess its a subject that the programming books tackle much sooner than its really necessary to. (As soon as chapter 3 in some books!!!!). And without reason to ACTUALLY use them at my current level of programming it just seemed kinda silly to me (though i did realize that they could be extremely useful for writing things like Game Engines and Libraries, and other things that i have YET to move on to in C++), and left me wondering, "Why so early on with such a dangerous and advanced concept?"

I guess i just felt like they were teaching me the basics of dancing when i haven't even learned to walk yet! Every book i have teaches pointers at least 2 sections before they even teach about "reference vs value" types
Last edited on
Here's a real life example for you.

The last time I worked with embedded Tigersharc processors, the board they were soldered to had an LED on it. That LED was a direct representative of an address in the memory the Tigersharc processor was using. One fixed location in the memory. The manual helpfully gave the address; I don't recall what it was, so let's say it was 0x3322FEED.

I controlled the LED state with a pointer.

1
2
3
4
5
6
7
8
int* pLedState;
pLedState = 0x3322FEED;

// Turn on LED
*pLedState  = 1;

// Turn off LED
*pLedState  = 0;


If you can think of a way to directly access a known, hard-wired memory address, without using pointers, I would like to hear it :)

Hard-wired memory addresses exist in hardware all over the place. The hardware inside the PC you're using right now has them. Lots of them.

"Why so early on with such a dangerous and advanced concept?"


They are not remotely advanced. They're simply not. A pointer is a variable just like any other. You create one, it exists in memory, you give it a value, you apply operators to it.

However, every use i've seen of pointers could be replaced with a variable...

Firstly, a pointer is a variable. To think otherwise is to fundamentally misunderstand what a pointer is in memory, which is asking for future trouble when you have to start using them.

Anyway, I presume you meant that you see no need to dynamically allocate memory on the heap when you could put the object you want on the stack. You go and allocate a variable of size one gig on the stack. See how well that works out, and then allocate it on the heap.
Last edited on
I guess i just felt like they were teaching me the basics of dancing when i haven't even learned to walk yet!
Unfortunately C++ and C are like that. The real problem is that programming books just focus on the programming syntax and how to use it. But you really need to understand the C virtual machine before you begin--that is, call stack, heap, functions, direct access memory.
kbw wrote:
But you really need to understand the C virtual machine before you begin--that is, call stack, heap, functions, direct access memory.

This is exactly why I usually encourage total beginners to learn C before learning C++!

Realize that C/C++ are close to the metal; so what do you find when you look at CPU-level instructions? Lots of indirection (aka pointers)! It turns out the pointers are extremely useful, if you know how to use them. Proponents of recent high-level VM-based GC-available languages would have you believe that pointers are dangerous and useless, but that's just propaganda (if you look at how they implement their VMs or GCs, of course they are using a ton of pointers). The dangers of pointers are overrated, if you are a disciplined C++ programmer.

Let me rephrase that - perhaps for a standard GUI app developer, you could live fine without pointers.

However, if you are doing high-performance server code or you are writing a compiler or domain-specific language, having pointers around to create, say, a jump-table is quite convenient.
90% of the time when I use pointers it's to work with polymorphism. If you are coming from C# then you must understand how polymorphism works.

For a basic example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Vehicle { };
class Car : public Vehicle { };
class Truck : public Vehicle { };

//  Car and Truck are both derived from Vehicle

// now say we want to create either a Car or Truck depending on what the user inputs...
Car user;  // this doesn't work if the user wants a truck

Truck user; // this doesn't work if the user wants a car

Vehicle user;  // this doesn't work because it's not a Car or Truck

// so how can we do it?  We use a pointer:
Vehicle* user;

if(user_wants_a_car)  user = new Car;
if(user_wants_a_truck)  user = new Truck;



Now in C# you could accomplish the same thing without pointers, but only because C# objects mimic being pointers behind the scenes. For example in C# you do the same thing without pointers:

1
2
3
4
// C#, but forgive me, my C# is rusty and I might be wrong
Vehicle user;
if(user_car)  user = new Car;
if(user_truck) user = new Truck;


This of course doesn't work in C++ because of an important language detail:

- In C#, objects are actually references to other objects, and not objects themselves
- In C++, objects are objects. If you want a pointer or reference, you have to explicitly say so.


Take another example:

1
2
3
// C#
Truck t = new Truck;
Vehicle v = t;


Here, in C#, 'v' and 't' would both refer to the same object. Changes made to 'v' would also affect 't'.

In C++ this isn't the case. If you do something similar in C++ you have a problem:

1
2
3
// C++ (probably bad code)
Truck t;
Vehicle v = t;


Here, in C++, 'v' is a copy of 't', and is a separate object. However only the Vehicle portion of the object has been copied. Any information specific to Truck has been lost in the copy.

To accomplish the same thing as the C# example in C++, you have to specifically tell C++ that you want a pointer/reference:

1
2
3
4
5
6
7
// C++ (using references)
Truck t;
Vehicle& v = t;

// C++ (using pointers)
Truck t;
Vehicle* v = &t;


The main difference between the two is that references can't be reseated (v will always refer to the t object), whereas with pointers you can reseat them (you can change v to refer to a different object if you like)
If you ever program data structures in c, you will see that you can't do much without pointers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//C#
using System;

public class Test {
	public int z;

	public static void Main() {
		Test a = new Test();
		a.z = 5;
		
		Test b = a;
		b.z = 10;
		
		Console.WriteLine( a.z );
	}
}
10


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

using namespace std;

int main() {
	int *a = new int;
	*a = 5;
	
	int *b = a;
	*b = 10;
	
	cout << *a << endl;
	
	delete a;
	return 0;
}
10

// C++ (using references)
Truck t;
Vehicle& v = t;

// C++ (using pointers)
Truck t;
Vehicle* v = &t;



The main difference between the two is that references can't be reseated (v will always refer to the t object), whereas with pointers you can reseat them (you can change v to refer to a different object if you like)



^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Thanks Disch... for an even more comprehensive explanation about why pointers are needed, i was completely unaware, of the fact that reference variables could not be reseated, and probably would have screwed up a lot of programs and not understand why....

Last edited on
Topic archived. No new replies allowed.