There are many uses. It greatly helps to understand the difference between the heap and the stack, and to understand the difference between static and dynamic allocation.
Functions in C are "pass by value" rather than "pass by reference". To simulate "pass by reference", the "value" you would pass is the memory address of the data in question, ie the pointer.
Also, if you put data on the heap, you must keep a reference to its memory address, otherwise you wont be able to access it again. You use a pointer for this. The following bit of code allocates some space on the heap, sticks an integer (5) on it and then returns a reference to that memory address, which is stored in a pointer variable named x.
int * x = new int(5);
To understand why you would do the above instead of "int x = 5", you really need to understand what the stack and heap are, and why/when to
use them.
Also, you can create read-only versions of variables this way. Eg:
int x = 5;
const int * y = &x;
At this point, y points to the address containing x, but can only be used to read. printing out "x" and "* y" will both give you the same result. If you want to update it, you can do "x=6", but "* y=6" will cause a compile time error, because of the const.
There are probably loads of other uses too. I only started learning C/C++ last month, in my spare time. Hmm, I seem to have learnt a few things.
Functions in C are "pass by value" rather than "pass by reference". To simulate "pass by reference", the "value" you would pass is the memory address of the data in question, ie the pointer.
Also, if you put data on the heap, you must keep a reference to its memory address, otherwise you wont be able to access it again. You use a pointer for this. The following bit of code allocates some space on the heap, sticks an integer (5) on it and then returns a reference to that memory address, which is stored in a pointer variable named x.
To understand why you would do the above instead of "int x = 5", you really need to understand what the stack and heap are, and why/when to use them.Also, you can create read-only versions of variables this way. Eg:
At this point, y points to the address containing x, but can only be used to read. printing out "x" and "* y" will both give you the same result. If you want to update it, you can do "x=6", but "* y=6" will cause a compile time error, because of the const.There are probably loads of other uses too. I only started learning C/C++ last month, in my spare time. Hmm, I seem to have learnt a few things.