Domanda

This is a little bit of a doozy of a coding problem I need help on - first the structures being used:

typedef struct node {
   char email[100];
} Node;

typedef struct edge {
   Node *from_email, *to_email;
} Edge;

Node nodes[NODE_ARRAY_SIZE];
Edge edges[EDGE_ARRAY_SIZE];

So, as you can see, the "Node" structure contains a char array with an email and the "Edge" structure contains pointers to 2 different Nodes. There are also two arrays, one of Nodes and one of Edges.

I would like to qsort() both arrays - I have already done the nodes one using:

qsort(nodes, node_size, sizeof(Node), node_cmp_function);
int node_cmp_function(const void *a, const void *b) {
  Node *temp_a = (Node *)a;
  Node *temp_b = (Node *)b;
  return strcmp(temp_a->username, temp_b->username);
}

but I cannot figure out how to sort the Edges array -> I'd like to sort it using strcmp on *from_email - but if both *from_emails being compared are equal, then I'd like to sort using *to_email.

Thanks for all the help!

È stato utile?

Soluzione

If I understand correctly what you're doing, something like this might work (untested code):

int edge_cmp_function(const void *a, const void *b)
{
    Edge *temp_a = (Edge *)a;
    Edge *temp_b = (Edge *)b;
    int result = 0;

    if ((result = node_cmp_function(temp_a->from_email, temp_b->from_email)) == 0)
    {
        result = node_cmp_function(temp_a->to_email, temp_b->to_email);
    }

    return result;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top