Hello there,
Pointers are an interesting concept within both C and C++. However, both languages actually handle the one feature differently, so what I tell you may well apply to C but not C++ and vice versa.
These two quotes from
The C Programming Language, 2nd Edition, give you a bit more insight into what they can do:
From those quotes alone, we can deduct that pointers and arrays have a very strong relationship, and from the other, we know that when used properly, our programs can actually be better.
In C(and I take it that it will be the same in C++), arguments are
passed by value to functions. Let's imagine I have a variable, stored in
F(), and within
G(), I want to alter the variable stored in
F(). Without pointers, my code will look something like this:
C:
#include <stdio.h>
int F() {
int a = 5;
printf("%d\n", G(a));
printf("%d\n", a);
}
int G(int x) {
x = 10;
return x;
}
My output is:
The reason why it comes out like this is because we're only passing a
copy of the variable, not the memory address where the original is stored - this is what's stopping us from altering it and the new value will not remain in place until the end of the progam. Fear not, we can easily change this:
C:
#include <stdio.h>
int F() {
int a = 5;
printf("%d\n", a);
G(&a);
printf("%d\n", a);
}
int G(int *x) {
*x = 10;
return *x;
}
What we've changed now is:
x is now a pointer. We'll pass the address of a so that we can have its value altered.
- Within the calling function(
F()), we've slightly reorganised it so that we see the original value of a first, call G() and pass the address of a, and then print out the altered value, which is now permanent and will remain in place until the program ends.
This is just one example of how pointers can be put to good use. They allow us to alter things in ways that certain limitations(like pass by value) impose on us.
C and C++ allow for many more things to be done with pointers, including using pointers instead of arrays for strings, pointers to functions(which allow you to pass functions as arguments to another function), and they're even used in handling commandline-arguments(i.e. this:
int main(int argc, char *argv[])).
If you are ever to work with memory, embedded systems, and operating systems, you'll find yourself to be using pointers a lot - particularly in conjunction with data-structures too. They are a core part of a C(++) program and will remain so for years to come.
C++, based on something that I discovered awhile ago(I recall reading that one shouldn't use pointers in C++), actually has two alternatives to pointers:
references and
smart pointers - both are apparently meant to be safer than just a regular pointer. Look into them and maybe delve deeper into C++'s handling of pointers, as what I've given you is based on my knowledge of C and not C++.
Either way, I hope this helps you to get an idea of how important pointers are and what they could possibly be used for.