0
int main ()
{
  int line,column,i,j;
  int sortir = 1;
  float nbr;

  cout << "The number of column :";
  cin >> column;
  cout << "The number of lines: ";
  cin >> line;
  float matrice [column][line];   //creating my 2d array

  for(i=0;i <= line;i++) //asking the user to put the numbers he wants in the 2d array
    for(j=0;j <= column;j++){
      cout << "Enter a number";
      cin >> nbr;
      matrice[j][i] = nbr;
    }
  system("PAUSE");
  return 0;
}

假设我做了一个 line = 1 和 column = 1 的数组,这使得(内存区域)[0,0] [0,1] [1,0] [1,1]。假设用户输入以下数字:

[0,0]=1

[0,1]=2

[1,0]=3

[1,1]=4

当我想向用户显示他在程序结束时输入的内容时:区域 [0][1] 和 [1][0] 显示相同的数字?

cout << matrice[0][0] = 1

cout << matrice[0][1] = 3 <-- why the f***

cout << matrice[1][0] = 3 <--His my for loop good?

cout << matrice[1][1] = 4
4

2 回答 2

2

您正在越界访问您的数组。你循环了太多的元素。你需要

for(i=0;i < line;i++) {
  for(j=0;j < column;j++){

除此之外,您的代码不是符合标准的 C++,并且依赖于称为可变长度数组(VLA) 的扩展。您不能声明具有在运行时确定的大小的自动存储阵列。

int i;
std::cin >> i;
int a[i];   // ERROR (non-standard VLA extension)
const int j = 42;
int b[j];   // OK
int c[42];  // OK
于 2013-09-14T22:48:07.573 回答
1

那不是有效的语法。 float matrice[column][line]是非法的。C++ 中不能有可变大小的数组。您的编译器提供了诸如扩展之类的功能。

于 2013-09-14T22:48:54.057 回答