Home >Backend Development >C++ >Understanding Pointers
In technology degrees, there are concepts and subjects that generally scare students, some of the main examples are subjects related to Object Oriented Programming and Calculus, another example are some more basic notions abstract structures such as pointers, mainly in C, the subject of this article.
Unlike us, computers do not know certain information by a “label” or “name”, but by the address where this data is located in memory. We can think of memory as a set of “cells” that contain a number of bits that store 0 or 1 and each cell is associated with a certain address where it stores some information so that programs executed by the machine can access this data and manipulate it. .
Bearing in mind that for a program to be able to use data it needs to know its address in memory, we can conceive the concept of a pointer. The pointer is a variable that “points” to some other data, it is as if it were a space in memory intended to store the address of another variable or information so that it can be manipulated.
But now the question comes, what is the use of a pointer? The pointer allows for some more complex operations involving memory, such as dynamic allocation with Malloc or the creation of more complex data structures, etc. Furthermore, there are some details that are not so easily noticed by students at first, such as the fact that the name of a vector is a pointer. That's right, a vector is nothing more than a “fixed pointer” that points to a certain position in memory and that we use the index to manipulate according to need.
Another use is manipulating data by reference, for example: passing an array as a parameter to another function, allowing the original array to be modified instead of the passed value or object being just a copy, something that, for example, occurs in Javascript where there is no there is a concept of a pointer (at least not explicitly), for example:
#include <stdio.h> int vet [5] ={10,20,3,4}; void somadez(int * ref){ for(int i=0;i<5;i++) ref[i]+=10; } int main () { somadez(vet); for(int i=0;i<5;i++) printf("%i\n",vet[i]); return 0; } saída: 20 30 13 14 note que quem foi alterado foi o vetor original
Another not so obvious use of pointers, this time for object-oriented languages, where we can, for example, create dynamic objects and facilitate work with inheritance and polymorphism.
We have this example below with C++:
#include <iostream> using namespace std; class Animal{ public: virtual void som(); }; class Cachorro : public Animal{ public: void som(){ cout << "auau"; } }; int main () { Animal * ClasseBase; Cachorro ClasseFilha; ClasseBase = &ClasseFilha; ClasseBase->som(); //neste caso podemos usar o ponteiro para acessar métodos e atributos de uma classe derivada. return 0; }
The above is the detailed content of Understanding Pointers. For more information, please follow other related articles on the PHP Chinese website!