Quote:
Originally Posted by FloydianOne
Can someone either explain to me, or give me a good site to learn how to do the following?
If I have an 2d array..
int [2][3] = {1,2,3,4,5,6};
How do I pass the array into a function which will switch the rows?
ie... row 0 is now row 1 and row 1 is now row 0.
|
My god, have you chosen the wrong language!
The short answer is that you can't do what you'e asking for in C.
Tha long answer is that you don't really understand what C arrays are or, even, what C is really about...
C is, basically, a high level assembler. More specifically, it is the last programming language that still understands the hardware it runs on. That's why it's so good for its original purpose, which was to write operating systems!
To better understand your current problem, you should have written your array initialization like so:
Code:
int array[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
While both your method and this method compile, this way shows you exactly what a multi-dimensional array really is:
An array of arrays.
You can't assign arrays to arrays, like you can with other variables, so you can't "swap" arrays in the manner that you imply. However, there are some work-arounds you can try. The most obvious one is to make a function that can copy one array to another, so you can swap the data of the two arrays in your multi-dimensional arrray.
Another, easier, work-around is to have an array of pointers to arrays, like so:
Code:
int *temp;
int line0[3] = { 1, 2, 3 };
int line1[3] = { 4, 5, 6 };
int *array[2] = { line0, line1 };
array[1][2] = 7; /* This will even compile! */
/* Swap the pointers in the array... */
temp = array[0];
array[0] = array[1];
array[1] = temp;
This only works because there's no real difference between arrays and pointers. I'm tempted to say you'd lose the bounds checking except that there was never any bounds checking to lose!
So, those are your options. I hope you learned something...
PS. Is anyone else annoyed by that "extra linefeed" bug in this BB code?