I am new to C++ and as I was reading MIT lecture note about pointer I recognize something strange:
Pointers are just variables storing integers – but those integers happen to be memory addresses, usually addresses of other variables. A pointer that stores the address of some variable x is said to point to x. We can access the value of x by dereferencing the pointer.
well and also I find that the pointer can have a type:
int *pointer ;
char * pointer ; //example
well it just said it's an int that hold an address why give it the same type as the thing it point at if it's just hold a reference to it not an actual value ?
Maybe you have an array of int. and "accidently" ... an array variable is a pointer to the first component of that array. With the knowledge of having a pointer being of type int, the compiler knows how far it must jump to the next data.
int a[4] = { 0, 1, 2, 3 };
// Dereferenced pointers to an int with additonal offset of size int n times
printf("%i\n", *a);
printf("%i\n", *(a+1));
printf("%i\n", *(a+2));
printf("%i\n", *(a+3));
// Equivalent to using the array as usual
printf("%i\n", a[0]);
printf("%i\n", a[1]);
printf("%i\n", a[2]);
printf("%i\n", a[3]);
This is an advanced example, but it is one of the seldom uses for an int pointer. Most often you will have pointers to objects, structs or arrays - seldom to the value types. But in some implementations of algorithms, pointers to value types can be usefull for sorting, searching etc. in arrays
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With