455

I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.

Basically I have three questions:

  1. Why use pointers over normal variables?
  2. When and where should I use pointers?
  3. How do you use pointers with arrays?
8
  • 8
    Discussed before at this question Hope that helps!
    – Doug T.
    Oct 2, 2008 at 15:20
  • 4
    For a list of books, see stackoverflow.com/questions/388242/… . After Java, I found Accelerated C++ very useful.
    – Jabba
    Jan 15, 2010 at 21:22
  • 263
    We use pointers because it's easier to give someone an address to your home than to give a copy of your home to everyone.
    – Rishi Dua
    Oct 4, 2013 at 14:51
  • 28
    @RishiDua That is the single best explanation of a pointer I have ever come across. Thank you for that, it has increased my understanding :)
    – Josh
    Nov 7, 2013 at 14:54
  • 3
    Pointers can also be used when you wish to return more than one value/object.
    – Gaurav
    Nov 27, 2015 at 6:00

17 Answers 17

224
  • Why use pointers over normal variables?

Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...

  • When and where should I use pointers?

Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.

  • How do you use pointers with arrays?

With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer. These declarations are very similar (but not the same - e.g., sizeof will return different values):

char* a = "Hello";
char a[] = "Hello";

You can reach any element in the array like this

printf("Second char is: %c", a[1]);

Index 1 since the array starts with element 0. :-)

Or you could equally do this

printf("Second char is: %c", *(a+1));

The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:

printf("Second char is: %s", (a+1)); /* WRONG */

But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?

char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);

This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).

Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:

char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);

Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.

20
  • 10
    Your example with 120 in it is wrong. It's using %c not %s so there's no bug; it merely prints the lowercase letter x. Moreover, your subsequent claim that a pointer is type int is wrong and very bad advice to give to a C programmer inexperienced with pointers. Jul 5, 2010 at 11:29
  • 14
    -1 You started well but the first example is wrong. No, it's not the same. In the first case a is a pointer and in the second case a is an array. Did I mention it already? It's not the same! Check for yourself: Compare sizeof(a), try to assign a new address to an array. It won't work.
    – sellibitze
    Sep 23, 2010 at 15:20
  • 13
    "It is not wrong or illegal to perform this printf statement". This is plain wrong. That printf statement has undefined behaviour. On many implementations it will cause an access violation. Pointers are not actually of type int, they are actually pointers (and nothing else).
    – Mankarse
    Aug 14, 2011 at 3:58
  • 19
    -1, You've gotten so many facts wrong here and I'll just flat out say you don't deserve the amount of upvotes or accepted answer status.
    – asveikau
    Jun 18, 2012 at 3:43
  • 7
    Section 6 of the comp.lang.c FAQ explains the relationship between arrays and pointers in C very well. This answer does not. May 30, 2013 at 18:56
62

One reason to use pointers is so that a variable or an object can be modified in a called function.

In C++ it is a better practice to use references than pointers. Though references are essentially pointers, C++ to some extent hides the fact and makes it seem as if you are passing by value. This makes it easy to change the way the calling function receives the value without having to modify the semantics of passing it.

Consider the following examples:

Using references:

public void doSomething()
{
    int i = 10;
    doSomethingElse(i);  // passes i by references since doSomethingElse() receives it
                         // by reference, but the syntax makes it appear as if i is passed
                         // by value
}

public void doSomethingElse(int& i)  // receives i as a reference
{
    cout << i << endl;
}

Using pointers:

public void doSomething()
{
    int i = 10;
    doSomethingElse(&i);
}

public void doSomethingElse(int* i)
{
    cout << *i << endl;
}
6
  • 27
    Probably a good idea to mention that references are safer, in that you can't pass a null reference. Oct 2, 2008 at 16:36
  • 37
    Yeah, that's probably the biggest advantage of using references. Thanks for pointing it out. No pun intended :)
    – trshiv
    Oct 2, 2008 at 17:19
  • 2
    You surely can pass null reference. It is just not as easy as passing null pointer.
    – n0rd
    May 30, 2013 at 20:54
  • 1
    concur with @n0rd. If you think you can't pass a null reference you're wrong. It is easier to pass a dangling reference than null reference, but ultimately you can do either easy-enough. References are no silver bullet protecting an engineer from shooting himself in the foot. See it live.
    – WhozCraig
    Sep 9, 2013 at 18:14
  • 5
    @n0rd : Doing that is explicitly undefined behaviour. Dec 20, 2013 at 14:04
51
  1. Pointers allow you to refer to the same space in memory from multiple locations. This means that you can update memory in one location and the change can be seen from another location in your program. You will also save space by being able to share components in your data structures.
  2. You should use pointers any place where you need to obtain and pass around the address to a specific spot in memory. You can also use pointers to navigate arrays:
  3. An array is a block of contiguous memory that has been allocated with a specific type. The name of the array contains the value of the starting spot of the array. When you add 1, that takes you to the second spot. This allows you to write loops that increment a pointer that slides down the array without having an explicit counter for use in accessing the array.

Here is an example in C:

char hello[] = "hello";

char *p = hello;

while (*p)
{
    *p += 1; // increase the character by one

    p += 1; // move to the next spot
}

printf(hello);

prints

ifmmp

because it takes the value for each character and increments it by one.

2
  • 1
    because it takes the value for each character and increments it by one. Is in ascii representation or how?
    – ESCM
    Jun 4, 2020 at 3:24
  • would p=0; reset the pointer?
    – GRquanti
    Mar 6, 2021 at 23:36
37

Pointers are one way of getting an indirect reference to another variable. Instead of holding the value of a variable, they tell you its address. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).

The best explanation of pointers and pointer arithmetic that I've read is in K & R's The C Programming Language. A good book for beginning learning C++ is C++ Primer.

1
  • 1
    thank you! finally, a practical explanation of the benefits of using the stack! does a pointer to position in an array also improve performance accessing the values @ and relative to the pointer?
    – user1382306
    Oct 2, 2013 at 4:34
28

Let me try and answer this too.

Pointers are similar to references. In other words, they're not copies, but rather a way to refer to the original value.

Before anything else, one place where you will typically have to use pointers a lot is when you're dealing with embedded hardware. Maybe you need to toggle the state of a digital IO pin. Maybe you're processing an interrupt and need to store a value at a specific location. You get the picture. However, if you're not dealing with hardware directly and are just wondering about which types to use, read on.

Why use pointers as opposed to normal variables? The answer becomes clearer when you're dealing with complex types, like classes, structures and arrays. If you were to use a normal variable, you might end up making a copy (compilers are smart enough to prevent this in some situations and C++11 helps too, but we'll stay away from that discussion for now).

Now what happens if you want to modify the original value? You could use something like this:

MyType a; //let's ignore what MyType actually is right now.
a = modify(a); 

That will work just fine and if you don't know exactly why you're using pointers, you shouldn't use them. Beware of the "they're probably faster" reason. Run your own tests and if they actually are faster, then use them.

However, let's say you're solving a problem where you need to allocate memory. When you allocate memory, you need to deallocate it. The memory allocation may or may not be successful. This is where pointers come in useful - they allow you to test for the existence of the object you've allocated and they allow you to access the object the memory was allocated for by de-referencing the pointer.

MyType *p = NULL; //empty pointer
if(p)
{
    //we never reach here, because the pointer points to nothing
}
//now, let's allocate some memory
p = new MyType[50000];
if(p) //if the memory was allocated, this test will pass
{
    //we can do something with our allocated array
    for(size_t i=0; i!=50000; i++)
    {
        MyType &v = *(p+i); //get a reference to the ith object
        //do something with it
        //...
    }
    delete[] p; //we're done. de-allocate the memory
}

This is the key to why you would use pointers - references assume the element you're referencing exists already. A pointer does not.

The other reason why you would use pointers (or at least end up having to deal with them) is because they're a data type that existed before references. Therefore, if you end up using libraries to do the things that you know they're better at, you will find that a lot of these libraries use pointers all over the place, simply because of how long they've been around (a lot of them were written before C++).

If you didn't use any libraries, you could design your code in such a way that you could stay away from pointers, but given that pointers are one of the basic types of the language, the faster you get comfortable using them, the more portable your C++ skills would be.

From a maintainability point of view, I should also mention that when you do use pointers, you either have to test for their validity and handle the case when they're not valid, or, just assume they are valid and accept the fact that your program will crash or worse WHEN that assumption is broken. Put another way, your choice with pointers is to either introduce code complexity or more maintenance effort when something breaks and you're trying to track down a bug that belongs to a whole class of errors that pointers introduce, like memory corruption.

So if you control all of your code, stay away from pointers and instead use references, keeping them const when you can. This will force you to think about the life times of your objects and will end up keeping your code easier to understand.

Just remember this difference: A reference is essentially a valid pointer. A pointer is not always valid.

So am I saying that its impossible to create an invalid reference? No. Its totally possible, because C++ lets you do almost anything. It's just harder to do unintentionally and you will be amazed at how many bugs are unintentional :)

1
  • You can write nice wrapper classes for memory-mapped IO with which you can essentially avoid the use of pointers.
    – einpoklum
    May 28, 2019 at 20:00
14

Here's a slightly different, but insightful take on why many features of C make sense: http://steve.yegge.googlepages.com/tour-de-babel#C

Basically, the standard CPU architecture is a Von Neumann architecture, and it's tremendously useful to be able to refer to the location of a data item in memory, and do arithmetic with it, on such a machine. If you know any variant of assembly language, you will quickly see how crucial this is at the low level.

C++ makes pointers a bit confusing, since it sometimes manages them for you and hides their effect in the form of "references." If you use straight C, the need for pointers is much more obvious: there's no other way to do call-by-reference, it's the best way to store a string, it's the best way to iterate through an array, etc.

0
12

One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.

Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:

unsigned char *pVideoMemory = (unsigned char *)0xA0000000;

Many embedded devices still use this technique.

1
  • Not a reason to use a pointer - a span-like structure - which also holds the length - is much more appropriate. These days it is gsl::span, and soon it will be std::span.
    – einpoklum
    May 28, 2019 at 20:02
11

In large part, pointers are arrays (in C/C++) - they are addresses in memory, and can be accessed like an array if desired (in "normal" cases).

Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.

If you want to do dynamic storage allocation (such as for a linked-list), you must use pointers, because they're the only way to grab memory from the heap.

5
  • 8
    I think it's misleading to say pointers are arrays. Really, array names are const pointers to the first element of the array. Just because you can access an arbitrary point as if its an array doesn't mean it is... you might get an access violation :)
    – rmeador
    Oct 2, 2008 at 15:51
  • 2
    Pointers are not arrays. Read section 6 of the comp.lang.c FAQ. May 30, 2013 at 18:57
  • Pointers are really not arrays. Also, there's not much use in raw arrays either - certainly not after C++11 and std::array.
    – einpoklum
    May 28, 2019 at 20:02
  • @einpoklum - pointers are close enough to arrays to be equivalent in reference operations and iterating through arrays :) ....also - C++11 was 3 years away from release when this answer was written in 2008
    – warren
    May 29, 2019 at 16:18
  • @einpoklum - it's obvious you hold a different view here.
    – warren
    May 29, 2019 at 20:53
10

Pointers are important in many data structures whose design requires the ability to link or chain one "node" to another efficiently. You would not "choose" a pointer over say a normal data type like float, they simply have different purposes.

Pointers are useful where you require high performance and/or compact memory footprint.

The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though.

9

One way to use pointers over variables is to eliminate duplicate memory required. For example, if you have some large complex object, you can use a pointer to point to that variable for each reference you make. With a variable, you need to duplicate the memory for each copy.

1
  • That's a reason to use references (or at most - reference wrappers), not pointers.
    – einpoklum
    May 28, 2019 at 20:03
7

In C++, if you want to use subtype polymorphism, you have to use pointers. See this post: C++ Polymorphism without pointers.

Really, when you think about it, this makes sense. When you use subtype polymorphism, ultimately, you don't know ahead of time which class's or subclass's implementation of the method will be invoked because you don't know what the actual class is.

This idea of having a variable that holds an object of an unknown class is incompatible with C++'s default (non-pointer) mode of storing objects on the stack, where the amount of space allocated directly corresponds to the class. Note: if a class has 5 instance fields versus 3, more space will need to be allocated.


Note that if you are using '&' to pass arguments by reference, indirection (i.e., pointers) is still involved behind the scenes. The '&' is just syntactic sugar that (1) saves you the trouble of using pointer syntax and (2) allows the compiler to be more strict (such as prohibiting null pointers).

5
  • 1
    No, you don't have to use pointers - you can use references. And when you write "pointers are involved behind the scenes" - that's meaningless. goto instructions are also used behind the scenes - in the target machine's instructions. We still don't claim to use them.
    – einpoklum
    May 28, 2019 at 20:03
  • 1
    @einpoklum-reinstateMonica If you have a set of objects that you want act on, assigning each element in turn to a temporary variable and calling a polymorphic method on that variable, then yes you NEED a pointer because you cannot rebind a reference.
    – Sildoreth
    Dec 12, 2019 at 13:57
  • 1
    If you have a base class reference to a derived class and call a virtual method on that reference, then the derived class' override will be called. Am I wrong?
    – einpoklum
    Dec 12, 2019 at 14:13
  • 1
    @einpoklum-reinstateMonica That is correct. But you can't change what object is referenced. So if you're looping over a list/set/array of those objects, a reference variable won't work.
    – Sildoreth
    Dec 12, 2019 at 23:03
  • I had an experience similar to this recently, except in my case I had a fake constructor-like static method in an abstract base class which had to create and return a new object of any one of a number of child class types. Couldn't use references because they have to be bound to a variable on the stack, and I can't return a reference to parent type because then the child methods would be sliced off (also, I can't pass a reference to a temporary when the whole point is to create a new object). Returning pointer to base it is :)
    – saxbophone
    Jan 27, 2021 at 21:55
6

Because copying big objects all over the places wastes time and memory.

4
  • 5
    And how does pointers help with that? I think a person coming from Java or .Net doesn't know the difference between the stack and the heap, so this answer is pretty useless.. Oct 2, 2008 at 15:24
  • You can pass by reference. That will prevent copying. Oct 2, 2008 at 15:25
  • 2
    @MatsFredriksson - Instead of passing (copying) a large data structure, and copying the result back again, you just point to where it is in RAM and then modify it directly.
    – John U
    Jun 25, 2012 at 13:00
  • 1
    So don't copy big objects. Nobody said you need pointers for that.
    – einpoklum
    May 28, 2019 at 20:05
6

Here's my anwser, and I won't promse to be an expert, but I've found pointers to be great in one of my libraries I'm trying to write. In this library (It's a graphics API with OpenGL:-)) you can create a triangle with vertex objects passed into them. The draw method takes these triangle objects, and well.. draws them based on the vertex objects i created. Well, its ok.

But, what if i change a vertex coordinate? Move it or something with moveX() in the vertex class? Well, ok, now i have to update the triangle, adding more methods and performance is being wasted because i have to update the triangle every time a vertex moves. Still not a big deal, but it's not that great.

Now, what if i have a mesh with tons of vertices and tons of triangles, and the mesh is rotateing, and moveing, and such. I'll have to update every triangle that uses these vertices, and probably every triangle in the scene because i wouldn't know which ones use which vertices. That's hugely computer intensive, and if I have several meshes ontop of a landscape, oh god! I'm in trouble, because im updateing every triangle almost every frame because these vertices are changing al the time!

With pointers, you don't have to update the triangles.

If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion.

0
6

The need for pointers in C language is described here

The basic idea is that many limitations in the language (like using arrays, strings and modifying multiple variables in functions) could be removed by manipulating with the memory location of the data. To overcome these limitations, pointers were introduced in C.

Further, it is also seen that using pointers, you can run your code faster and save memory in cases where you are passing big data types (like a structure with many fields) to a function. Making a copy of such data types before passing would take time and would consume memory. This is another reason why programmers prefer pointers for big data types.

PS: Please refer the link provided for detailed explanation with sample code.

2
  • The question is about C++, this answer is about C.
    – einpoklum
    May 28, 2019 at 20:06
  • nope, question is tagged c AND c++. Maybe the c tag is irrelevant, but it's here from the start. May 28, 2019 at 21:08
3

In java and C# all the object references are pointers, the thing with c++ is that you have more control on where you pointer points. Remember With great power comes grand responsibility.

2

Regarding your second question, generally you don't need to use pointers while programming, however there is one exception to this and that is when you make a public API.

The problem with C++ constructs that people generally use to replace pointers are very dependent on the toolset that you use which is fine when you have all the control you need over the source code, however if you compile a static library with visual studio 2008 for instance and try to use it in a visual studio 2010 you will get a ton of linker errors because the new project is linked with a newer version of STL which is not backwards compatible. Things get even nastier if you compile a DLL and give an import library that people use in a different toolset because in that case your program will crash sooner or later for no apparent reason.

So for the purpose of moving large data sets from one library to another you could consider giving a pointer to an array to the function that is supposed to copy the data if you don't want to force others to use the same tools that you use. The good part about this is that it doesn't even have to be a C-style array, you can use a std::vector and give the pointer by giving the address of the first element &vector[0] for instance, and use the std::vector to manage the array internally.

Another good reason to use pointers in C++ again relates to libraries, consider having a dll that cannot be loaded when your program runs, so if you use an import library then the dependency isn't satisfied and the program crashes. This is the case for instance when you give a public api in a dll alongside your application and you want to access it from other applications. In this case in order to use the API you need to load the dll from its' location (usually it's in a registry key) and then you need to use a function pointer to be able to call functions inside the DLL. Sometimes the people that make the API are nice enough to give you a .h file that contain helper functions to automate this process and give you all the function pointers that you need, but if not you can use LoadLibrary and GetProcAddress on windows and dlopen and dlsym on unix to get them (considering that you know the entire signature of the function).

2
  • In some cases, function pointers are required to use functions that are in a shared library (.DLL or .so). This includes performing stuff across languages, where oftentimes a DLL interface is provided.
  • Making compilers
  • Making scientific calculators, where you have an array or vector or string map of function pointers?
  • Trying to modify video memory directly - making your own graphics package
  • Making an API!
  • Data structures - node link pointers for special trees you are making

There are Lots of reasons for pointers. Having C name mangling especially is important in DLLs if you want to maintain cross-language compatibility.