The pointer is a variable like any other, but it stores a memory address that references another place of memory where the content is.
Examples:
in C:
int * a = malloc(10 * sizeof *a);
in C++:
int * a = new int[10];
the variable to is a pointer that stores the memory address for the 1st vector position. The rest of the positions are accessed by means of basic arithmetic, see this answer: /a/80097/3084
Pointers have 4 bytes on a 32-bit architecture and 8 bytes on a 64-bit architecture. Note that they will always have the same size, no matter what type of variable they point to. Thus, a char pointer is the same size as a double pointer.
Considering a 32-bit architecture, in the above example, the variable to is a 4 byte pointer pointing to a vector that uses 10*4 = 40 bytes of RAM (a int on a 32-bit architecture also uses 4 bytes of memory to be represented).
Updating
Even when you just declare the pointer (without pointing it to any memory address), as below:
int * a;
the same 4 bytes of RAM are used. However, in this case, the vector is pointing to a random memory address.
the same happens if you do so:
int * a = NULL;
however, in this case, the vector is pointing to the address 0.
Anyway, the 4 bytes of memory are spent anyway.
The syntax shown is not C. I think you meant
int *a = malloc(10 * sizeof *a);
– pmg
Thank you @pmg. I have included the two examples.
– cantoni
@pmg, edited. I switched sizeof *a (according to its edition), to sizeof(int). In this case, take sizeof(int) and multiply by 10.
– cantoni
Hmmm ...
*a
has kindint
, so much sosizeof *a
assizeof (int)
are correct. I prefer to use the object itself to, in case of changing the type, only need to change the code in one place:double *a = malloc(10 * sizeof *a);
vsdouble *a = malloc(10 * sizeof (double));
– pmg
Ahh ok! You’re right! It really avoids two changes. I’ll change. Thanks again.
– cantoni
It just needs to be clear that this consumption of the 4 bytes (8 on 64 bit architectures) is relative. There is consumption but no direct allocation. If it is in the stack this is already allocated. If it is in an area of heap, it has already been allocated by the object containing it.
– Maniero
Thanks @bigown, I even started writing the memory area where usually the pointer is stored (stack), but I think it deserves to be better explored and I won’t have time now. As soon as I have time I’ll update.
– cantoni