coder1212
coder1212

Reputation: 19

allocating memory for vectors

Can anyone tell me why this program is crashing? Basically I was trying to create a vector of arrays?

#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;

int main() {
    vector <int> arr[100];
    arr[0][0] =5;
    printf("%d",arr[0][0]);

    return 0;
}

Upvotes: 0

Views: 224

Answers (2)

Matthieu Brucher
Matthieu Brucher

Reputation: 22033

You are creating an array of 100 empty vectors, not a vector of arrays (why not a vector of vectors?). There is nothing there to use.

Use this:

vector<vector <int>> arr(100, vector <int>(size));

with size the size you require.

If you want a vector of arrays, use:

vector<array<int, 100>> arr(size);

Upvotes: 5

grapes
grapes

Reputation: 8646

Because you did not allocate elements in vector. You are confusing std::vector with static arrays, they need calling .push_back() or doing a prealloc.

So in your code arr[0] will work because this is a reference to first element of static array, while arr[0][0] is crashing.

Try

arr[0].push_back(5)

Upvotes: 2

Related Questions