![]() |
[C] 2d array pointers
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. I know its something to do with pointers and double pointers, and I tried to read a few sites about them... but it just ended up confusing me more, none of them had any good examples. I thought it would be something like this... Code:
int array[2][3] = {1, 54, 98, 2, 75, 84}; |
Quote:
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 } }; 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; So, those are your options. I hope you learned something... PS. Is anyone else annoyed by that "extra linefeed" bug in this BB code? |
See the problem is that this is an assignment and the teacher sent a template, that we are to finish. And well she hard codes the definition of the array to just be a 2d array and not a array of pointers.
Since we havent learned anything about malloc or memcopy, and she says we cant change the template... Im assuming the only way I can do this is hardcoding saying element 0 = element 3 etc. etc. I plan on going to get help from the class TA tomorrow. Thanks for your help though.... even though I havent figured out exactly how to do it, ive learned alot about pointers etc. |
Well if that's the case don't forget a temp variable to hold one value while swapping.
|
C will let you do anything, good or bad. The only difficult thing about it is consistently describing what you want done in ways that others can figure out.
"I always liked C, unless it's someone else's C." Somewhat cruel she sent you on this quest without first drowning you in pointer math. That must be next. Have fun. And resist swap stunts. |
Quote:
...and I do hope you learned somethng... |
All times are GMT -8. The time now is 06:58 AM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project