-1
int main(){
setlocale(LC_ALL, "");
cout << sizeof(Livro);
paragrafo();
int cont;
Livro *livros;
while(true){
int op;
cout << "1) Maior de 3 números";
paragrafo();
cout << "2) Preencher vetor de livros";
paragrafo();
cout << "3) Listar livros preenchidos";
paragrafo();
cout << "4) Gravar vetor de livros";
paragrafo();
cout << "5) Ler vetor de livros";
paragrafo();
cout << "0) Sair";
paragrafo();
cin >> op;
switch (op){
case 1:
cout << "opção escolhida 1\n";
maiorDe3();
break;
case 2:
cout << "opção escolhida 2\n";
if(cont == 0){
cout << "caiu na primeira\n";
livros = new Livro[cont + 3];
registrarLivro(&cont, &livros[cont]);
}
else if(cont > 0){
cout << "caiu na segunda\n";
Livro *livrotemp;
livrotemp = new Livro[cont + 10];
registrarLivro(&cont, &livros[cont]);
for(int i = 0; i < cont; i++){
livrotemp[i] = livros[i];
}
delete [] livros;
livros = NULL;
livros = new Livro[cont + 4];
cout << " MEMORIA ALOCADA " << cont + 4 << " ";
for(int i = 0; i < cont; i++){
livros[i] = livrotemp[i];
}
delete [] livrotemp;
livrotemp = NULL;
}
I would like help in this part of my code, I tried to make a memory allocation for a struct so that this allocation is deleted and increased to each new book added in the struct, but it is not working the memory allocation does not increase according to the cont variable, which is the amount of books that are recorded.
Thank you very much, your post was perfect I didn’t know of these C++ utilities to work with vector growth and you gave me new ideas on how to do this, I think the way I was looking for was a thought more geared up by ultimatizing C. One last question, in its item 4 when using the new to define the space of cont + 4 in memory, let’s assume cont = 10, was allocated a Book vector with 14 positions in the right memory? I can’t dislocate that memory and allocate again later with a larger cont? To have more positions.
– Arthur Vieira
Yes it can displace, in the function of item 3, vc passes 3 parameters : the current vector, size of the current vector and the new size the call is like this :
livros = realocaVec(livros, cont, cont + 10 ) ; cont = cont + 10;
this function already displaces the previous one in the controldelete [] l
. So you don’t even need the book and the body ofelse if(cont > 0)
is minuscule. With the exception of the Cout << "allocated memory" line... The whole paragraph is reduced only to this call, since theLivro *livrotemp;
up to thelivrotemp = null
.– Cleiton Santoia Silva