What is the reason why a vector with no set size does not work?

Asked

Viewed 248 times

1

If you create a vector:

Thus int Vetor[0]; works

#include <iostream>

using namespace std;

int main()
{
    int vetor [1];
    vetor[0] = 12;

    cout << vetor[0] << endl;
}

Thus int Vetor[]; does not work and error

#include <iostream>

using namespace std;

int main()
{
    int vetor[];
    vetor[0] = 12;

    cout << vetor[0] << endl;
}

error: Storage size of ːvetor' isn’t known|

I just wanted to understand that. What is the importance of having a number inside the []?

  • C++ . pq when I leave without setting it does not work.

  • 1

    Enter the code and error.

  • error: Storage size of ːvetor' isn’t known|

  • ready edited... the only doubt is to understand this

  • If you translate the error, you might better understand the error.... "the 'vector' storage size is not known"

  • The problem has already been solved. I understood by the explanation given by bigown . It was only to know the importance of having an index that defines the size of the vector. Valeu ae!

Show 1 more comment

1 answer

3


When we declare a variable we are reserving a memory space for it, nothing else. And the line int vetor []; is just the statement, nothing more.

By obvious the syntax of the declaration of a array requires you to know what kind of data it will contain, and this has, we know it’s a int and that it’s probably 4 bytes in size (it’s a little more complicated than this, but that’s not the case here), and we need to know how many elements you’ll have in the array to multiply by 4 and know how many bytes need to be allocated. Where is this absolutely necessary information? There’s nothing you can do to fix this.

In the example that works it has the size 1, which multiplied by 4 indicates that the variable will have 4 bytes reserved in memory. All you need to know the size you will allocate.

You can even set the size when allocating through a variable, but you can’t be left with nothing.

It is possible that the compiler will even discover the size by itself depending on the syntax:

int vetor[] = { 1, 2, 3 };

I put in the Github for future reference.

Thus vetor will have size 3, and will reserve 12 bytes in memory for this variable, and will automatically put the values above.

  • Understood. Thank you very much !! ;D

Browser other questions tagged

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