Discussion Locked

applying same logic once for 2 fields

0 helpful
1 reply
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I am writing a simple ansi c program. I have a link list(say X) having two integer fields(say a and b) for each node. I have to sort them separately but the sorting logic is same. so i need a function which'll be called from main. now in my sorting function if i want to sort field "a" then i have to refer it as X.a. also for "b" it is X.b
naturally i am writing samething twice(one for "a" and one for "b") .
Can anyone say that how can I accept "a" or "b" as variable, so that for sorting "a" or "b" i have to write code only once.

1 reply

by shajithchandran

you can do this easily by using the offset of the variables. Suppose the struct which you are using is as given below.
struct node{
int a; // offset is zero;
int b; // offset is sizeof(int);
struct node *next;
};

Now in the sorting function instead of using the operator '<' directly, use a function called compare. This function should take the pointers to the nodes to be compared and the offset. Now in the compare function you have to type cast these pointer to int* and add the offsetand compare the values.
I hope you got my point.

This discussion is closed to new replies.