for example, given a matrix:
1 2 3
4 5 6
7 8 9
if you are goint to swap row[0] and row[1], resulting matrix would be:
4 5 6
1 2 3
7 8 9
can you guys help me get a code in C for this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The answer depends entirely on how your “matrix” is implemented, because the c language has no notion of such a thing.
Are you using two dimensional arrays?
Or something else?
Two dimensional arrays
You will have to move individual elements by hand.
(here
r1andr2are ints that have been set to the two row you want to swap) or see James’memcpyimplementation which may well be faster but requires a whole rows worth of temporary memeory.Ragged Arrays
If this operation is very common and profiling reveals that it is consuming a lot of time, you might consider using a ragged array implementation of the matrix. Something like this:
The fun part about this structure is that you can still access it with the
[][]notation, but the row swap operation becomesRagged arrays have two disadvantages from your point of view (well, three ’cause of the memory management hassle): they require extra storage for the row pointers, and you can’t use inline initialization.
Row-as-astructure
C does not support array assignments of the form;
but it does support by-value assignment semantics for structures. Which gives you the implementation that several people have suggested without explaining:
which is slick. It requires a whole row of memory, but if the compiler is any good is probably fast. The big disadvantage is that you can not address individual matrix elements with the
[][]syntax anymore. Rather you writem[i].r[j];Others
There are many, many other ways to implement a “matrix” in c, but they are mostly much more complicated and useful only in specialized situations. By the time you need them you’ll be able to answer this questions for yourself in the context of each one.