The pointers are one of the great potentials of C and C ++ because they come from C because I inherit them, but it is a characteristic of C. You have a confusion in the way pointers work, the pointers are a type of data which only a memory address can be saved, that is, pointers (pointers) to a memory address, a memory address that has already been assigned to another variable or dynamically ( Memory Management ), but it must be a memory address that exists and has already been assigned . When you define a pointer it always has the characteristic asterisk before the name, and to use it you can do it in different ways, besides with the pointers you can use something called Arithmetic of pointers , with an extremely basic example that may help put you in context:
int numeroINT = 100;
double numeroD = 50.025;
const char *texto = "En C no existe el objeto de alto nivel llamado String";
int *ptrInt = &numeroINT;
double *ptrD = &numeroD;
As you can see, I declare two variables, a int
and the other type double
, and a constant pointer to char
which points to a text string, which can not be changed because it is a constant pointer .
Two pointers are declared, one to type int
and another to type double
, and these are passed the memory address of two variables of the same type, so those pointers are pointing to the memory address of those two variables.
Now with these two pointers you can modify the two variables, because the pointers have their memory address already assigned, following the previous example:
void imprimir_texto(const char *texto)
{
printf("%s\n", texto);
}
void aumentar_numero(int *numero)
{
++(*numero);
}
imprimir_texto(texto);
//Estas dos llamadas son equivalentes
aumentar_numero(ptrInt);
aumentar_numero(&numeroINT);
Take a look at these two functions, one receives a constant pointer to char
and prints it, and the other receives a pointer or memory address to a data type int
, and its value increases it by 1 .
When a pointer is used, it is done in two ways, one is to use it without the asterisk, this means that it is being called to the memory address, but if you put the asterisk, you are calling it at < strong> value saved in that direction, are two very different pods.
What are the advantages of using pointers, it is a question I asked when I saw them for the first time, suppose that you have an incredibly large and heavy structure and it requires that you go through many functions, the values passed to functions are passed by value, that is, that a copy of the original object is made and the copy is passed, and if your structure is very large, that copy will take its time, considerably lowering the performance, a simple solution to this is to pass the memory address (pointer) of the structure , with this the original is passed instead of making a copy, adding this you can protect the original structure against copy by adding the reserved word const
in front of the definition, in the same way that I did with the text.