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

1

Here's 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 'vector' is not known |

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

    
asked by anonymous 02.08.2017 / 23:14

1 answer

2

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

Obviously the statement syntax of a array requires you to know the type of data it will contain, and this has, we know that it is a int and that it is probably 4 bytes in size (it's a bit more complicated than that, but it does not matter here), and we need to know how many elements will have in the array to multiply by 4 and know how many bytes need to be allocated. Where is this information absolutely necessary? You do not have it and there's nothing to do to resolve it.

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

You can even set the size at the time of allocating through a variable , but you can not run out of anything .

It is possible for the compiler to even find the size alone depending on the syntax:

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

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

    
02.08.2017 / 23:36