Reputation: 19
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
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
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