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 functions 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 rather 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:
#includeint vet [5] ={10,20,3,4}; void somadez(int * ref){ for(int i=0;i 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:#includeusing namespace std; class Animal{ public: virtual void som(); }; class Cachorro : public Animal{ public: void som(){ cout som(); //neste caso podemos usar o ponteiro para acessar métodos e atributos de uma classe derivada. return 0; }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3