I don't know what's wrong with my array.

This program's supposed to ask for the size of a given seat plan and the seating arrangement (numbers), then it's supposed to ask how many times to swap, then it's supposed to ask which seats are to be swapped then it should display everything in the end. I'm not sure why, but it seems like I'm accessing data that's out of my array.

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	int c, r, numswap, swap1, swap2, swap1r, swap1c, swap2r, swap2c;
	cin >> r;
	cin >> c;
	int seats[r][c];
	for(int x = 0; x < r; x++) 
	{
		for(int y = 0; y < c; y++)
		{
			cin >> seats[r][c];
		}
	}
	cin >> numswap;

	for(int z = 0; z != numswap; z++)
	{
		cin >> swap1;
		cin >> swap2;
		for(int x = 0; x < r; x++) 
		{
			for(int y = 0; y < c; y++)
			{
				if(seats[x][y] == swap1)
				{
					swap1r = x;
					swap1c = y;
				}
				if(seats[x][y] == swap2)
				{
					swap2r = x;
					swap2c = y;
				}
			}
		}
		seats[swap1r][swap1c] = swap2;
		seats[swap2r][swap2c] = swap1;
		
	}
	for(int X = 0; X < r; X++)
	{
		for(int Y = 0; Y < c; Y++)
		{
			cout << seats[X][Y] << " ";
			if(Y == c-1)
			{
				cout << endl;
			}
		}
	}
	
	
}

I tried changing [X] and [Y] to just [2] and [3], but this is how it looked like:
3 4
11 12 13 14
15 16 17 18
19 20 21 22
4199448 4199448 4199448 4199448
4199448 4199448 4199448 4199448
4199448 4199448 4199448 4199448

I have no idea where 4199448 came from. Can someone tell me where I went wrong?
On line 16 you're inputting into seats[r][c]. You should input into seats[x][y].
Umm... why does Line 11 not give an error.

The dimensions of the array should be constants not variables. Variable size is only allowed when we allocate the array dynamically! How come the code even compiles?
The dimensions of the array should be constants not variables. Variable size is only allowed when we allocate the array dynamically! How come the code even compiles?


Some common compilers allow this, but you're right; the standard does disallow it.
> Some common compilers allow this

Only if do not ask them to conform to the standard.
First of all, you should never create an array like you are doing here.

Arrays need to be created using constants, not variables. You should always use dynamic allocation whenever ever you need to create an array, whose size is unknown until run-time.

Secondly, on line 16, you are inputting to index [r][c] instead of [x][y].
Not necessarily. GCC will allow this by default. You need to specifically tell it to not allow it.
Thanks. Wow I feel really stupid for not seeing that. I'm very new to C++.
Topic archived. No new replies allowed.