Uses for Pointers

Pages: 123
They can't have different values.


pntr = NULL;
Do they still have the same value?
Yes, you are right. But, what I meant is that as long as pntr is pointing to cSomething instance, anything changed on pntr will have the same effect on cSomething, because pntr points to cSomething.
You use the pointer to get the object to change, you don't change the pointer. If you change the pointer it will point to something else.
But why would you need to use a pointer to change an object if you can just change the object directly without one?
if you can just change the object directly
¿But how do you know what object you want to change?
Think about the relationships between objects and how you could transmit messages.

Considerer a graph, ¿how could you obtain the neighbours of a node?
But why would you need to use a pointer to change an object if you can just change the object directly without one?


int* p = new int;
Go on then, change the value of that int without using a pointer.

Last edited on
Also, try to build a fully-functional linked-list without pointers.

Edit: Another use for pointers is iterators.

Wazzak
Last edited on
You could make a fully functional STATIC linked list with references... >:)
int* p = new int; That's a terrible example. There is no advantage against int p;
The point is to illustrate the futility of the question
But why would you need to use a pointer to change an object if you can just change the object directly without one?


Would you prefer this instead?
int* p = new int[10000000];
Go on then, change the value of that int without using a pointer.
Last edited on
@OP: IMO the most useful aspect of a pointer is something called a Callback function. This is where you have a function that you as the programmer have defined and you set it to execute as part of a larger process. These are all over WinAPI but the most famous has to be WndProc which handles the messages given to your Windows application from the Message queue. This allows us to make WndProc into what ever we want it to be, handle messages how ever we want and we aren't hindered by some arbitrary size or limited in anyway. This allows the Operating System to interface with our program at any point it wants to without causing any critical errors and by extension it allows our program to interface with, well everything.

Pointers are how the C Family does DMA (Direct Memory Access). This allows variables to leave their scope, it allows singletons to be interacted with outside of their initialized area, it allows the size of an array or in some cases even variables to be determined at run time, it allows threads, process and even systems to communicate with eachother when they would otherwise be limited by Memory Protection constraints... there are honestly too many uses to list in one thread like this.

well no its not exactly the same, but either way x gets the value of y.
maybe I was thinking of &y = *x.


That would be an error. You're attempting to change the address of a variable declared on the stack, which is static in memory.
Since this thread is still kicking, here's an attempt at a more comprehensive answer

Raw ("C-style" or "naked" or "dumb") pointers have many low-level uses, and it may be difficult to figure out what is what.

1) Handler to dynamic object

The new-expression (e.g. new Type(args)) always returns a raw pointer, therefore pointers must be used to track objects that have dynamic storage duration. Such pointers are usually wrapped in appropriate self-managing "smart" pointer types, such as std::auto_ptr, boost::scoped_ptr, or std::unique_ptr.

2) Copyable handler to a polymorphic object

Many tasks dealing with runtime polymorphism, e.g. implementing a container of non-owned polymorphic objects, require the use of raw pointers as handles to such objects, regardless of their storage duration. References can be used for runtime polymorphism as well, but not when a container needs to be implemented.

3) Rebindable reference

Several forms of class relationships in OOP design are expressed with pointers because they can be used as rebindable references. Raw pointers, in particular, are best when expressing non-owning aggregation, or child to parent association. (in this use, pointers sometimes compete with std::reference_wrapper. If ownership needs to be expressed, raw pointers are not used; owning pointers such as unique_ptr, shared_ptr, weak_ptr are used instead)

4) Optional type

Pointers can serve as "maybe'" types because they can point to an object or be null. In this role, they compete with boost::optional and other third-party "maybe" types.

5) Callback

Pointers to functions may serve as lightweight delegates or callbacks. They compete with function objects in this role, which are in fact more common because they can be stateful.

When C code is used in C++, pointers may also be used:

6) C alternative for references

C has no concept of pass-by-reference, so it had to simulate it by passing pointers to functions. A lot of code that was ported from C to C++ uses pointers in this role.

6) Iterators for C-style arrays

Pointer to T can be used as a random-access iterator to a C-style array of T, so the C code that uses arrays (and C++ code that uses C-style arrays for whatever reason) almost always uses pointers as iterators. This is the only case where pointer arithmetic can be used: pointers to elements of an array, like any random-access iterators, may be incremented by an integer, decremented by an integer, and subtracted from each other.
Last edited on
int* p = new int; That's a terrible example. There is no advantage against int p;

Yeah thats what I was thinking.

int* p = new int[10000000];
Go on then, change the value of that int without using a pointer.

If that makes int p[10000000] then I would do p[1] = 4;

So how I see it, & returns the address of a variable, and * returns the value stored at the address which equals value of variable.
So if
1
2
int x;
std::cout << &x;

it returns the address of x, and if I do this
1
2
3
int * y;
*y = 1232;
std::cout << *y

It returns the value stored at adress 1232?
Last edited on
Yeah thats what I was thinking.


No, you were thinking that there was no use in having pointers as you could always change the value directly. I gave you a very, very simple example where you couldn't do that. Next time I'll just draw you a diagram.
I dont really know what I was thinking anymore, pointers are just a very difficult concept for me to grasp.
The idea behind pointers is being a dynamic reference to other objects.

Memory allocation itself is possible without pointers, but dynamic memory allocation needs you to store the location of that memory you just created. What do you store them in? A variable. Just a regular variable. What kind of variable? The kind commonly known as a "pointer" (C/C++) or "reference" (Java). (Note that a "reference" is different in C++ than in Java)

Pointers can also be used as DDRs (dangerous dynamic references) to stack-allocated data. I say dangerous because, how do you know when that data is destroyed? You don't, so unless you make sure you set the pointer to 0/null when the object is destructed, the pointer could be dangling (pointing to memory that your program no longer owns or controls)

Task: write a linked list. Post here when you get stuck.
Last edited on
I dont really know what I was thinking anymore, pointers are just a very difficult concept for me to grasp.


Do you understand what an int is? A pointer is remarkably similar.

Did you read this yet? http://www.cplusplus.com/articles/EN3hAqkS/
A great example of how pointers can be used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    #include <iostream>

    using namespace std;

    // Prototype:
    void DoubleMyValues(int *a, int b);

    int main()
    {
        int Mrs_Int = 5;
        int Mr_Int  = 5;

        cout << "Pre-Double:\n";
        cout << "Mrs_Int: " << Mrs_Int << ", Mr_Int: " << Mr_Int << "\n\n";

        // - Passing Mrs_Int by ADDRESS
        // - Passing Mr_Int by VALUE
        DoubleMyValues(&Mrs_Int, Mr_Int);

        cout << "Post-Double:\n";
        cout << "Mrs_Int: " << Mrs_Int << ", Mr_Int: " << Mr_Int << "\n\n";

        return 0;
    }

    // - POINTING to the address of Mrs_Int
    // - COPYING the value Mr_Int
    void DoubleMyValues(int *Mrs_Int, int Mr_Int)
    {
        *Mrs_Int *= 2; // ..the same as '*Mrs_Int = Mrs_Int * 2;'
         Mr_Int *= 2;
    }


If you run this code you'll get this output:

Pre-Double:
Mrs_Int: 5, Mr_Int: 5

Post_Double:
Mrs_Int: 10, Mr_Int: 5


Since Mr_Int was passed in by value, the variable that was doubled inside of the function was actually a copy of Mr_Int with the same value. This is why when everything is printed out the second time in main(), Mr_Int is still 5 because it was only the copy inside of DoubleMyValues() which was doubled.

Basically, you can alter variables via functions if you pass them in by address and then point to them inside the function - even if the function returns nothing (void)! Remember that functions can only return one value, so to change multiple things you have to use pointers (..or references).

EDIT: Clarification.
Last edited on
That's a terrible example, references can just as easily be used and without the need to use * or & with the variables.

The real reason to use pointers in function parameters is to allow the parameter to be null, thus being an Optional parameter. In all other cases you should pass by value or by reference to simplify code and guarantee required variables.
Last edited on
Pages: 123