Pointers

What's exactly the use of pointers in coding?
Last edited on

jabeh (2)
What's exactly the use of pointers in coding?


in 'coding' ... some languages hide pointers entirely from the coder. Some languages rely on them as a key feature. C++ splits the difference.. you can do a lot without a single pointer at all. So the answer depends a lot on the language, but from a c++ perspective the above link is good info.

A short list of things you can do with them in c++ include:
polymorphism
serialization
chained datastructures (graphs, nonbinary trees, ...)
parameter passing (there are a couple of one-off scenarios where doing it any other way is convoluted)

there are also the C uses of pointers that C++ inherits, which can be used to build low level tools. It is unusual to need to do this, but it is supported.
Thanks joinni, by the way can you provide any code example using pointers, especially the short list you provide. can you give me some code please.
if you have a struct, you can cast its address to char* to write to a file (serialization)
somefile.write((char*)&somestruct, sizeof(somestruct_type));

a non-binary tree:
struct node
{
int data;
node* children[10]; //can be a vector but its still going to be a vector of pointers.
};

polymorphism... if you read far enough it will start using pointers to base classes and such.
https://www.geeksforgeeks.org/polymorphism-in-c/

as a parameter to a function:
double d[1000];
for(double &z:d) z = something;
...
memset(&d[42], 0, sizeof(double)*1000); //the first parameter is a pointer...
Last edited on
pointers are used to point.
it's the way to define relationships between objects beside composition and inheritance.

1
2
3
4
5
6
7
8
9
10
11
class school_bus{
   std::vector<child *> passengers; // a school bus transports children
public:
   void aboard(child *c){
     passengers.push_back(c);
   }
   void crash(){
     for(auto c: passengers)
       c->die();
   }
};
Topic archived. No new replies allowed.