Array don`t work correct

Hello everyone!

Why this don't work?
Someone helpe me please!!

The return is:
b[0][0] = 0
b[0][1] = 1
b[0][2] = 2
b[0][3] = 3
b[0][4] = 5
b[1][0] = 5

b[1][1] = 6
b[1][2] = 7
b[1][3] = 8
b[1][4] = 9

When I would like to see this:
b[0][0] = 0
b[0][1] = 1
b[0][2] = 2
b[0][3] = 3
b[0][4] = 4
b[1][0] = 5
b[1][1] = 6
b[1][2] = 7
b[1][3] = 8
b[1][4] = 9

Thanks,

Yuri.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int main(int NumberofArgs, char* pszArgs[])
{
    int a[9];
    int b[1][4];
    int original = 0;
    
    for (int i = 0 ; i < 10 ; i++)
    {
        a[i] = i;
        cout << "a["<<i<<"] = "<<a[i]<<endl;
    }
    
    cout << "\n\n";    

    // THIS DONT WORK. WHY??
    for (int i = 0 ; i < 2 ; i++)
    {
        for (int j = 0 ; j < 5 ; j++)
        {
            b[i][j] = a[original++];
        }
    }
    
    // ITS WRONG!!!!
    for (int i = 0 ; i < 2 ; i++)
    {
        for (int j = 0 ; j < 5 ; j++)
        {
            cout << "b["<<i<<"]["<<j<<"] = "<<b[i][j]<<endl;
        }
    }
        
    system("PAUSE");
    return 0;
}
If you declare an array as T array[n];, n being a constant, you can only use elements array[0] through array[n-1].
For example,
1
2
3
4
int array[2];
array[0]=0; //OK
array[1]=0; //OK
array[2]=0; //Illegal. Buffer overflow. 
To follow up what helios said, I recommend that you use constants throughout so that you aren't getting mixed up. Use the same constant for array creation as you do within the loops.

For instance, consider the following code. I didn't compile that but I think you'll get the idea and you can apply it to your example with the 2D array.
1
2
3
4
5
6
7
8
9
10
const unsigned int SIZE(10);  // use whenever you want to prevent buffer overflow
int SomeArray[SIZE];
std::generate(SomeArray, SomeArray + SIZE, rand); // fill with random values

// loop and print.
for(int i = 0; i < SIZE; ++i)
{
   std::cout << SomeArray[i] << " , ";
}
std::cout << std::endl;
Topic archived. No new replies allowed.