Explain the use of Pointers?

I just started with c++ and when I read about "Pointers" I got really confused.

Could somebody explain to me why you should use a pointer for variables and structs?
All arrays are pointers, array[5] is the same as *(array + 5). It's just a different way to say it.

That being said I don't see much use for them now either, but that probably just means I haven't learned enough to know the answer to your question.
Pointers become useful when you get to OOP. They can be used to hold valuable information when programming. Say for example you are reading in values from a very long string; and you want to change one char in the string depending on the other chars in the string, and you don't know where this character could be located. You can set a pointer to the address of that value and as the code progresses, you can just change that pointer and the value it is set at is changed also.

Pointers are also useful when you don't know the size of a container used in a program at compile time. You can declare a pointer of that type and during runtime, you can use the new keyword or malloc to allocate enough space to store information needed.

Pointer can be deleted and reused again during runtime.
In other words sometimes you need the program to change where it gets it's data in runtime and a static reference like arrayofdata[5] in the code won't cut it. Of course I suppose arrayofdata[variable] would do...
I think a lot of times when you can write something more than one way it's due to the language changing but still having to be compatible with older versions.
arrays are of course not pointers, and haven't been since the B programming language

pointers are difficult because they are semantically overloaded: they represent several completely different things, depending on how they were created and used. Some, but not all of these things are:
1) handle to a dynamic object: this kind of pointer is produced by new and eventually wrapped in a smart pointer or consumed by delete
2) rebindable reference: this kind of pointer is common in class design, e.g. consider a node of a tree that needs to refer to its children, but they can change any time if the tree is rebalanced
3) copyable reference: this kind of pointer may be used to hold polymorphic objects in containers
4) "maybe" types: this kind of pointer can be used to represent an object or no object, since pointers have that special "null" value.
5) bidirectional iterator in a C-style array: this kind of pointer is produced by taking the address of an array element or by conversion from array name, this is the only kind of pointer you can use pointer arithmetic on.
(and, lastly, in C, pointers were used to simulate pass-by-reference semantics, to avoid copying function arguments when calling functions -- cnoeval below describes this usage)
Last edited on
Dont ever overlook pointers. When it comes to OOP they are so useful! Pointers is quite a large spectrum so use your friend (Google) theres so much info out there is hard to not find anything on pointers. You might not get them at first but just stick with it, you will most definitely will come to use them in the future!
"arrays are of course not pointers"

Isn't it accurate to say that the name of an array is a pointer to it's first index and the [] brackets are an offset operator where array[5] and *(array+5) are equivalent?
Pointers may seems like confusing computerese but they're really something we use all the time in everyday life. The syntax can be confusing but the underlying concept is simple.

Many beginners think they're silly. WHY should I use pointers to tell my function where to look for the object I want that function to work on when I can just pass in the object itself??? The answer is because there is overhead involved in passing objects around, especially if they're very big.

Take an example of having something in your house break and you need to fix it. If the object is small (DVD player, toaster), you pick it up and take it to the repair shop. You just passed the object (toaster) to the function (repair) BY VALUE.

But what if your roof has a hole in it? Most houses won't fit in the trunk of your car. So, you call the repair shop and give them the ADDRESS of your house (you point to it) and they come out and do their function (repair) on the object (house roof) BY REFERENCE.

Same with your programs. If your object is a list of 10 names to be sorted, just pass it to the function. But if your object is a list of all the names in the U.S., you pass its location in memory to the function and it goes and works on the list in place at that memory address. Otherwize you would have to make a copy of that big list which would slow down your PC.

Obviously this is somewhat of a simplification but I hope you get the... well, you know.
agnophilo wrote:
Isn't it accurate to say that the name of an array is a pointer to it's first index

No, this is wrong. By that logic, the name of a floating-point number is an integer with its fractional part truncated (since you can write double d = 3.14 int n = d; and get 3). There is a big difference between "is" and "can be converted to"
Last edited on
cnoeval thank you very much, that was an extremely useful and detailed answer : ) Will have to copy/paste that somewhere.


And to Cubbi are you saying that if I write:

int array[5];
int*pointer = &array[0]
*(pointer+5) = 10;

that I am converting one data type into another?
@agnophilo
Functionally, you are constructing an iterator, and using it to write to memory one past the end of the array (which is an error, of course), It's the same as if you have a vector and you call .begin() on it, or a C++ array:

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
#include <iostream>
#include <vector>
#include <array>
int main()
{
    // vector
    std::vector<int> a1(5);
    std::vector<int>::iterator i1 = a1.begin();
    std::vector<int>::iterator i2 = std::begin(a1);
    *(i1+4) = 10; // let's pretend you didn't write +5
    i1[4] = 10;

    // C++ array
    std::array<int, 5> a2;
    int* i3 = a2.begin();
    int* i4 = std::begin(a2);
    *(i4+4) = 10;
    i3[4] = 10;

    // C-style array
    int a3[5];
    int* i5 = a3;
    int* i6 = &a3[0];
    int* i7 = std::begin(a3);
    *(i5+4) = 10;
    i6[4] = 10;
    i7[4] = 10;

    std::cout << a1[4] << a2[4] << a3[4] << '\n';
}

online demo: http://ideone.com/9vqc2o

this is the usage number 5 in my list above.

Now, if you want to be unnecessarily pedantic, yes, in the statement "int*pointer = &array[0];" you're constructing a pointer that points to the first element of the array (as part of the type conversion required to call operator[]), then you're adding zero to it, which has no effect, dereferencing it to obtain a reference to the first element of the array, then you're constructing a new temporary pointer with operator&, and then you're using that pointer to copy-initialize a named pointer called "pointer".
The code you wrote is a little advanced for me (not all the way through the tutorial on this site yet) and yes *(pointer + 1) would be out of the range of the array, but that is a typo that has nothing to do with the concept.

I googled iterator and apparently it's an advanced concept I've yet to get to so I will copy/paste your answer and review it later when it will make sense. Thank you for taking the time to explain it.
The easiest way to explain pointers, and how i understood them easily, is that pointers are variables that store another variable's memory address. You can use pointers to change the values of memory on the memory address. Saying:
1
2
int x;
x=5;

this can be done with pointers too! But before that, here's some syntax.
to declare a pointer, you add an asterisk after declaring the data type. Example int *pointer; declares a pointer that points to an integer, and string *pointer; declares a pointer that points to a string. Now, to manipulate the values inside the pointer, we use special syntax. Here's how to do that:
1
2
3
4
5
int x;
int *p_x=&x; /*i use p_ prefix to indicate that something is a pointer. Notice
the '&' sign. You can read it as 'address of' because that operator returns the memory address of a given variable. */
*p_x=5;  /*Notice the asterisk. It's not because p_x is a pointer. You can read it as 'value of', because then you can edit the contents of a memory address*/
/* It's like saying 'The value on the memory address 'p_x' is 5*/

Now to explain the '*p_x=5;' line a bit better. 'Value of' p_x returns the value of the memory address that the pointer is pointing to. From this example, the pointer is pointing to the address of 'x'. Then we use '=' as any other time we would make a variable equal to a number. After that we don't use any other special syntax. If you didn't understand all of this, re-read it, because pointers can be a bit confusing. Don't go jumping to pointers and arrays, because that way you won't understand it as you should. This is a basic pointer explanation, but this will help you a lot. After understanding this, you can continue working with pointers.

THE USE OF POINTERS

Even if you understood what i wrote before, you might want to ask "Why would i complicate things like that? Why wouldn't i just write 'x=5;'?"
Well, here's a reason, sometimes you need to pass on a big structure or array to a function. But here's a problem-every time you use them in functions, you need to copy the contents of the structure or array, but with pointers, you are just sending the address of the structure. This is useful because your program will run much faster. This may not look very attractive to you right now, but it will later.
Another use of a pointer is-i'll explain it on an example. Let's say you need to declare an unknown sized array. We usually use just the biggest value possible, like 'int array[10000]', but sometimes this isn't efficient. You will learn how to do this later, because it is complicated, but it is nothing to be afraid of, and you will learn how to use pointers properly and efficiently. I hope this helps ^_^.
Last edited on
This line will only confuse potential beginners even more. It also will generate a build error as a type redefinition.

??? -
Example int *pointer; declares a pointer that points to an integer, and string *pointer; declares a pointer that points to an integer.


Please be careful.
Last edited on
Topic archived. No new replies allowed.