Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of pointers? [duplicate]

Tags:

c++

pointers

What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?

like image 816
Babiker Avatar asked May 12 '09 01:05

Babiker


People also ask

What is the point of pointer variables?

A pointer variable (or pointer in short) is basically the same as the other variables, which can store a piece of data. Unlike normal variable which stores a value (such as an int, a double, a char), a pointer stores a memory address. Pointers must be declared before they can be used, just like a normal variable.

What is the point of pointers in coding?

Pointers are used to store and manage the addresses of dynamically allocated blocks of memory. Such blocks are used to store data objects or arrays of objects. Most structured and object-oriented languages provide an area of memory, called the heap or free store, from which objects are dynamically allocated.

Are pointers copied?

One function passes a pointer to the value of an object to another function. Both functions can access the value of that object, but the value itself is not copied.

What is the point of pointers in C++?

Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.


2 Answers

Pointers are best understood by C & C++'s differences in variable passing to functions.

Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively).

But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array? Passing it by value would be foolish: why would you copy 20 megs for this operation, and if you end up modifying it (i.e. it's an out-parameter) you have to copy that 20 megs BACK?

Better is to just "point" to it. You say, "here's a pointer to a big blob of memory". And that little indirection saves a ton of time.

Once you understand that, everything else is basically the same. Rearranging items in a list becomes just swapping pointers rather than copying every item around, you don't need to know how big things are when you start out, etc

like image 128
Matt Avatar answered Oct 21 '22 04:10

Matt


Pointers are most useful when dealing with data structures whose size and shape are not known at compile-time (think lists, trees, graphs, arrays, strings, ...).

Edit

These related answers might also help (the top answer in the second link is definitely worth a look):

In C++ I Cannot Grasp Pointers and Classes

What are the barriers to understanding pointers and what can be done to overcome them?

like image 31
Lance Richardson Avatar answered Oct 21 '22 06:10

Lance Richardson