I've seen that there is a quite similar question here: Dynamic array in C cause segmentation fault by that it's on C using malloc and I didn't understand the answers. I'm starting to learn programming and I'm just beginning to study arrays, I'm afraid I don't understand well how it works. I'm trying to create a square dynamic array. I'm trying to do it using pointers and 'new' to point to a var to get its size. I don't understand why my code (compiles with no warnings) doesn't work, it crahes after the user entered the value of size. That's what I have:
int main(){
int **dyn_array=nullptr; //dynamic multidimensional array pointer to pointer
int *rows_cols=nullptr; //pointer to var with number of rows that wil be introduced by the user
int n_elements=0;
rows_cols = &n_elements; //now the pointer points to memory location of var with number of rows/cols
dyn_array = new int *[n_elements]; //pointer of array now points to pointer of rows/cols var to get its size
cout << "ENTER A EVEN NUMBER OF ELEMENTS FOR A SQUARE ARRAY: " << endl;
cin >> *rows_cols; //the value entered by the user its assigned by the pointer to var that its assigned as size of the array
dyn_array[n_elements][n_elements]={0}; //It crashes. Why? I don't understand...
return 0;
}
Thank you very much. (excuse my english, i'm learning yet).