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;
}

Lets say I do an array of line = 1 and column = 1 which makes (memory zones) [0,0] [0,1] [1,0] [1,1]. Let's say the user inputs these following numbers:

[0,0]=1

[0,1]=2

[1,0]=3

[1,1]=4

When I want to show the user what he inputted at the end of the program: the zone [0][1] and [1][0] show the same number?

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
3
  • 1
    Avoid two dimensional arrays. See this answer Commented Sep 14, 2013 at 22:46
  • 3
    If an array has size N, you can't store N+1 elements in it. Commented Sep 14, 2013 at 22:47
  • 2
    C++ doesn't have built-in dynamically sized two dimensional arrays. If the above code compiles, you are using a compiler extension. Commented Sep 14, 2013 at 22:47

2 Answers 2

2

You are accessing your array out of bounds. You loop over too many elements. You need

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

Besides that, your code is not standards compliant C++, and is relying on an extension called variable length arrays (VLA). You cannot declare an automatic storage array with a size determined at runtime.

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
Sign up to request clarification or add additional context in comments.

Comments

1

That is not valid syntax. float matrice[column][line] is illegal. You cannot have variable sized arrays in C++. Your compiler is providing such as an extension.

2 Comments

You can of course create variable length arrays on the heap, using the new keyword. float* arr = new float[length];
Before you do, make sure you learn the delete command as well. new and delete always go hand in hand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.