【发布时间】:2019-01-27 20:14:26
【问题描述】:
我已经看到这里有一个非常相似的问题:Dynamic array in C cause segmentation fault 它是在 C 上使用 malloc 的,我不明白答案。 我开始学习编程,我刚开始学习数组,恐怕我不太了解它是如何工作的。 我正在尝试创建一个方形动态数组。我正在尝试使用指针和'new'来指向一个var来获取它的大小。 我不明白为什么我的代码(编译时没有警告)不起作用,它在用户输入大小值后崩溃。 这就是我所拥有的:
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;
}
非常感谢。 (对不起,我的英语,我还在学习)。
【问题讨论】:
-
你创建了一个大小为 0 的数组。