Good afternoon Vitor,
I’m going to divide the answer into two parts to make it clear.
- Dynamic allocation of memory
The main advantage of dynamic allocation is to work with only the required amount of memory, thus avoiding the waste of memory.
Example:
Let’s assume that we want to make a simple application that registers an N number of students, N being an unknown number.
typedef struct{
char nomeAluno[30];
int idadeAluno;
}cadastroAluno;
int main(){
cadastroAluno novoAluno[100];
return 0;
}
The code excerpt above is a alocação estática
memory, where we create a certain struct
and then we have a vector of 100 positions of this type of data, which means that, whenever the application runs, it will allocate the amount of memory equivalent to 100 times mine struct
, which is not always convenient. Why allocate 100 struct
if you don’t use all that amount?
It is in this context that the alocação dinâmica
memory is needed. Since you can reserve only the space needed to meet your need and avoid memory waste.
Pointers are tools for direct memory manipulation, since it is a type of data that receives memory addresses as a parameter and accesses them directly.
The great differential of its use is program performance gain.
when you speak of "allocation" you refer to dynamic allocation, static or both?
– H.Lima
I declared the Structure as pointer and made structurename=malloc(sizeof(Structure)).
– Vitor Gonçalves
I just knew I had to make it work, when I was learning c, in c++ I have no idea. must be something like new, but tmb do not know the reason.
– Vitor Gonçalves
I pointed an answer, if there is still any doubt about pointers and dynamic allocation put a comment I edit to complement the answer
– H.Lima
Since you are also asking about C++, nowadays it is hardly necessary to give a 'new'. Containers do everything without you using pointers (internally used). Do a search for containers in C++, such as vector, map, etc
– Kevin Kouketsu
So my problem is how to do this, I’m for example doing a program that reads 2 sets, in the class I declare for example a float vector that has [100] positions so I can store the typed numbers, how would I allocate it dynamically? using new for example, should I allocate the object or variable? this makes it difficult for me to visualize and even run. @H.Lima
– Vitor Gonçalves
If your question is about dynamic allocation, make it clear by editing it, and detailing your doubts. The way you are I can’t quite figure out exactly what you’re asking and what you really mean by "allocation"
– Isac
I want to understand in general what is allocation / pointers, I thought I had put everything in question. But what I said in the comments seems to be topic for another subject.
– Vitor Gonçalves