Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type of the pointer [duplicate]

Tags:

c++

pointers

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 ad­dresses, 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 ?

like image 823
Hesham Adel Avatar asked Nov 11 '22 12:11

Hesham Adel


1 Answers

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

like image 116
Marcel Blanck Avatar answered Nov 15 '22 05:11

Marcel Blanck