Helps in allocating memory for a struct

Asked

Viewed 33 times

-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.

1 answer

1


C++ is a language other than C, in C++ :

1 - You can encapsulate the Cout << "..." and the paragraph() in a single function ( wondering which paragraph will jump to next line" )

template<typename T>
ostream& out( ostream& o, const T& t ) {
  return o << t << "\n"; 
}

2 - If you can, avoid these "raw" pointer access structures, create a vector

int main() {
   std::vector<Livro> livros;
   livro x;   // sem new, sem ponteiros
   livros.push_back(x); // aloca mais um espaço e copia o livro no vetor;    
   foo( livros[0] ); // chama função passando o livro "x"
}  // quando sai do escopo, livros vai ser apagado automaticamente sem delete[] 

3 - Your "vector Grow" algorithm should be in a separate function from the rest of the code, a possible implementation would be :

Livro* realocaVec(Livro* l, int tam_antigo, int tam_novo )  {
  Livro *result = new Livro[tam_novo];    // nada bom...
  std::copy_n( l, tam_antigo, result );   // include <algorithm> ok !
  delete [] l;                            // nada bom...
  return result;
}

In this example above, you at least isolate the vector copy of the "record" function that I have no way of knowing what it is doing. Apparently, by the parameters, you must be inserting information in the second parameter and increasing the first one by 1 am right ? This has nothing to do with vector growth.

4 - Now the problem must be related to the command

livros = new Livro[cont + 4];

Suppose that cont = 10, in this case you have allocated a 14 position vector and I ask : in which variable is the number 14 ? None so far.

In your example, you have cont as variable with the amount of books allocated, but it is not clear whether it is the same as the amount of books used. Normally you need 2 variables one "size" with the actual size of the vector allocated and a "cont" with the amount of items already used and when vc will insert one more element in the vector and occur (cont == size) vc calls realocaVec, making the size a little bigger than the cont.

(warning only that this function is already very well developed within the class Std:vector)

  • 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.

  • 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 control delete [] 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 the Livro *livrotemp; up to the livrotemp = null.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.