Discuss ANSI C: Array element swapper in the C Programming forum on Dev Shed. ANSI C: Array element swapper C programming forum discussing all C derivatives, including C#, C++, Object-C, and even plain old vanilla C. These languages are low level languages, and used on projects such as device drivers, compilers, and even whole computer operating systems.
Posts: 17
Time spent in forums: 7 h 40 m 44 sec
Reputation Power: 0
ANSI C: Array element swapper
Hello, I am trying to write a function which swaps values. This will be used in a sorter I am writing for a school project.
Currently I can sort by swapping the actual values, ie if
a and b are integers, I can swap them with this code:
Code:
void swap( int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}
But that only works for nice simple number arrays. Now I need to apply this to an array list, where the elements are structures and not integers.
I realized that if I can simply swap what each element points to, then I can do this very easily.
ie my_struct[1] points to structure_a
and my_struct[2] points to structure_b
then if I can swap it so that it now goes like this:
my_struct[1] points to structure_b
my_struct[2] points to structure_a
I can easily swap elements in the array of structures without lengthy tedious copying of values, and instead simply redirect pointers.
However, I am having difficulty figuring out how to perform this task, and was hoping someone could help me by modifying the piece of code I wrote so that it worked in the manner I am shooting for. Then I will be able to see how it works, and adjust it appropriately to fit the program that I am writing.
Posts: 17
Time spent in forums: 7 h 40 m 44 sec
Reputation Power: 0
Quote:
Originally Posted by Annie79
Is this what you want?
c Code:
Original
- c Code
void swap(struct my_struct* a, struct my_struct* b){
struct my_struct* c;
c = a;
a = b;
b = c;
}
Thank you, but that doesn't seem to work. That seems to correctly redirect the pointers in the swap() function, but not the pointers that was sent to it.
if we pretend there is a line of yarn from
int1 and int2, to the memory that holds their values, then I want the program to clip the ends of the line of yarn, and move it over to the other address. So each variable now points to the thing in memory that the other guy used to point to. This way I don't have to change any data at all.
I'm not sure if this can be done, because I don't really know how arrays work. If they are just the next consecutive spot in memory, then I don't think my plan will work, because if I reorder what element points to what memory, they won't be consecutive anymore, and the array won't be able to get from one element to the next :/
But I'm hoping that isn't the case.
Anyway, thank you for spending time on it, even though it wasn't exactly what I was looking for.