Need Help in Explaining Pointers Please

I am still trying to understand pointers so please excuse me if this post about them doesn’t make sense.

I have been reading from my textbook along with some different sites and I still don't understand the when and why for using them.

From what I have gotten, you can dynamically allocate memory (which is a topic that I need to understand on its own, so please help), use it to point to data structures to save time and resources, and being able to obtain and display the memory address that a variable is on.

These statements about pointers might be wrong which also means that I am not fully understanding what they are. Currently, I am explaining to myself that they are variables that can point to an address.

Please correct me on anything that is false and explain to me:
1) When is the best time to use them?
2) What is dynamic memory allocation?
3) Why use pointers?

Thank you and sorry for this long and whiny post, I just want to get this down.
variables that can point to an address.

Correct.

1) When is the best time to use them?


When you need to and have no other option or when it is preferable.

2) What is dynamic memory allocation?


Sometimes memory needs can be only determined at runtime. So lets say I wanted a program to get input and store it, I could define a large array but that array might be filled up so I would use dynamic allocation, so when I need memory to store input I will allocate it and construct my memory. If you have used std::string or std::vector then those are classes that allocate their memory, they can determine how much memory they need at runtime.

http://www.cplusplus.com/doc/tutorial/dynamic/

Why use pointers?

When you need to.

Pointers are very powerful.
Last edited on
Pointers are variable ,
generally 4 bytes but ... it might depends on x64 and x86 architectures ,
that contains the address of block (s) in memory ( RAM ) .

A pointer can be initialized like that :

int numberOfPeople = 5;
int* ptr = &numberOfPeople // <- pointer containing the address (location) where the integer called numberOfPeople is at.

The reason to have that is that we knows then the exact location (which by the way is always random at runtime -> RAM ) , so we can access directly to its content (if we can of course -> see private , protected , public ... )

There is 4 operators (methods) to tell the compiler to allocate/desallocate the pointer dynamically in the heap :
new , new[] , delete and delete[] .

For every new there is a delete .

C++ does not contains garbage collector.

Why use pointers ? There is many reasons , including for dynamic allocation.

OOP : class , encapsulation , inheritance , polymorphism .
Polymorphism ? -> then you should use pointers (or reference but that 's another thing)











Damage control inbound.

generally 4 bytes
Not anymore. 64-bit OS use in the desktop market has likely since well overtaken 32-bit. Windows had been quickly reaching the 50% mark back in 2010.

A pointer can be initialized like that
Code tags, please.

which by the way is always random at runtime -> RAM
Uh, no. Not all virtual addresses are to physical random access memory.

The reason to have that is that we knows then the exact location, so we can access directly to its content
This is misleading. A better explanation would be that this way, we can have a sign that says "your car is there" rather than needing to remake the car every time you need it or some variation on it.

if we can of course -> see private , protected , public ...
These restrict access to private members from outside an object. It is still very much possible to get the addresses of protected and private members and dereference them freely.

There is 4 operators (methods)
These two terms are not interchangeable.

to tell the compiler to allocate/desallocate the pointer dynamically in the heap
Imprecise. Rather, they either allocate memory and return a pointer, or free the memory that a pointer is pointing to. Subtle wording differences like that can make all the difference to a beginner.

For every new there is a delete.
I wish. I've been meaning to have a firm conversation with a wide variety of game developers about that.

@OP
Actually on topic, there's a use for pointers that I haven't seen discussed here, and that's when you want a reference to something, but also want to have the option of not referencing anything (null). Some people call this a failing of programming languages to provide such functionality, but I strongly disagree. Example:
1
2
3
4
5
6
7
8
9
10
11
12
struct Ure{
    int foo;
    int bar;
};

int* lookup(const Ure& data, const std::string& name) {
    if(name == "foo")
        return &(data.foo);
    if(name == "bar")
        return &(data.bar);
    return nullptr; //I don't know what you wanted, so you're not getting anything.
}


-Albatross
Last edited on
Speaking of damage control:
1) When is the best time to use them?
When you need to and have no other option or when it is preferable.

The same could be said for using airplanes, butter knives or formal attire.
Why use pointers?
When you need to.

Ditto. If you aren't going to be helpful, please be silent.

Okay back to the original question. Why use pointers?

Technically, you can point to any memory location, but the most common use of pointers is for dynamic memory allocation. You probably already know how to create variables at compile time:
1
2
int a = 0;
double numbers[10];

But sometimes you don't how many variables you will need at compile time. So you want to tell the program to allocate room for your data while the program is running. For example, suppose you have a text file of numbers. The first line tells you how many numbers there are, and the rest of the file contains the numbers themselves. You might read them into an array allocated at runtime:
1
2
3
4
5
6
unsigned int num;
cin >> num;
double *arr = new double[num];
for (int i=0; i<num; ++i) {
    cin >> arr[i];
}


The standard library has a template called vector<> that handles this sort of automatically expanding array for you.

Another trick is to create a class or struct that contains a pointer. This lets you chain dynamic memory together:
1
2
3
4
5
6
7
class Link {
public:
    Link(int n) : val(n), next(NULL) {}
    int n;
private:
    Link *next;
};


Now you can declare one variable to point to a single link:

Link *head = NULL;

and string integers together in a chain called a linked list:
1
2
3
4
5
6
void add(int n)
{
    Link *tmp = new Link(n);
    tmp->next = head;
    head = tmp;
}

add() creates a new Link and adds it to the front of a chain of links. head always points to the front.

There are more complicated structures that work off this basic idea: you allocate data that contains pointers to other data.

That's a top-level view. The underbelly of dynamic memory allocation is that you have to tell the program when you're done with it so it can be returned to the "free pool" and potentially allocated again. If you forget to do this you can end up with a "memory leak" or you might just run out of memory.

Well that's the elevator speech. I hope this helps.




Last edited on
Topic archived. No new replies allowed.