Pointer Variables

I do not understand pointer variables at all. My book tried to explain it, but I have no idea. Things like this :

1
2
3
int* nVar = pnVar;

//so on and so forth  
closed account (28poGNh0)
Lets take this exemple

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

int main()
{
    int nbr = 45;
    int *ptr = &nbr;

    cout << nbr << endl;// This is the value of nbr
    cout << &nbr << endl;// This is it adress
    cout << *ptr << endl;// *ptr points to the address of the variable nbr(&nbr) 
                         // so it takes the value of nbr 45
    cout << ptr << endl;// the prof ptr(the address of *ptr) is the same with &nbr(address of nbr)

    return 0;
}


if you need more explanation just ask

hope it helps
Last edited on
I think I understand. So the int nbr is 45, and *ptr points to the address of nbr. mmmk
closed account (28poGNh0)
Yes a pointer is always? pointing to an address
Last edited on
Are you familiar with functions at all? Functions can help clarify the meaning of a pointer.

A basic function for say, adding 500 to an integer could look like this

1
2
3
4
int addNum(int x)
{
     return (x + 500);
}


When this function is called, you would pass a value for x. This value of x is copied and then 500 is added to it and then returned.

This is called passing by value, because you made a copy of the value you wanted to add 500 to.

Now lets say we wanted to pass using a pointer. It may look something like this

1
2
3
4
5
6

void pointerNum(int* x)
{
     *x += 500;
}


Notice how I did not return anything? Well, this is because I pulled the actual address of the variable and then used the deference operator to modify the variable. So this was not passed using a copy but passed by the address location, then modified.

The reason I explained this is to help understand why we use pointers. We use them because it is faster and uses less memory to pass around data. When dealing with a lot of data it uses a lot of resources to pass the data on top of trying to allocate more memory to make copies to modify it. Instead, you can modify it directly by knowing where it exists in memory and then knowing how to change it(deference).

In short, it is like emailing you a URL to a website instead of emailing the whole website to you.









Last edited on
Topic archived. No new replies allowed.