So, I need to create a square matrix with a size entered by user (also filled with random numbers). I tried this:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int size;
cin >> size;
int arr[] = {};
for (int i = 0; i < size; i++){
cout << endl;
for (int j = 0; j < size; j++){
arr[i][j] = rand() % 10;
cout << arr[i][j] << ' ';
}
}
return 0;
}
However, every time my g++ output is :
6.cpp: In function ‘int main()’:
6.cpp:12:21: error: invalid types ‘int[int]’ for array subscript
arr[i][j] = rand() % 10;
^
6.cpp:13:29: error: invalid types ‘int[int]’ for array subscript
cout << arr[i][j] << ' ';
Where have I messed up?
int arr[] = {};I'm not even sure this is valid, but regardles off that indexingarrwill return an int, you're trying to index the int. This cannot work.int arr[] = {}std::vector. If you ae not allowed to usestd::vectorfor some reason, it gets trickier. Note the declared-but-unimplemented copy constructor and assignment operator in the linked code. This is the secret sauce to making an easy-to-use matrix around a pointer.std::vectordoes all this for you.