How to: Define and Use the Pointers Variables in C++

2 comments - This post in romanian

The pointer type variables allow the accessing of memory areas with numerical content for the management of the values which represent memory addresses. The dimension of a pointer variable depends on the processor architecture.
In the C++ programming language, the definition template of a pointer variable is:

TipData *Den_VarPointer;

Examples:

int *pi;//pointer to int
char **ppc;//pointer to char* (pointer \
to pointer of char)
float *pv[20]//array with 20 elements of float* type \
(array with 20 pointers to float)

The initiation of a pointer variable is made through the following methods:

  • Attributing an existing memory address;
int i=1, *pi;
pi=&i;
  • Taking over a heap memory address after the calling of standard/ allocation operator functions.
int *pi;
pi=(int*)malloc(sizeof(int));//allocation of heap memory \
with standard functions; it is allocated space in heap for \
1 element of int type

or:

int *pi;
pi=new int;//allocation of heap memory with operator; \
it is reserved in heap space for 1 element int type

The usage of a pointer variable involves the allocation of the * operator for extracting the content from the address stored in the pointer variable.
Example for accessing the content from the address stored in a pointer variable:

int i=1, *pi;
pi=&i;//storage of memory address of the variable i \
into pointer variable pi;
*pi=2;//content modification from memory adrress \
stored in pi; effect: variable i accessing the memory area \
with value 2

For a pointer variable, the value 0 represents the null value. A pointer value which contains the value 0 specifies the fact that it does not store a memory address.
When a heap memory area is not useful for the application, it is de-allocated by the standard function free or the delete operator.

, , , , ,