John has already answered your question, but to sort your struct
s, you can use the standard library qsort()
function:
#include <stdlib.h>
#include <stdio.h>
struct MyStruct {
int iID;
int iMyNumber;
};
/* comparison function, should return < 0, > 0 or == 0
if a < b, a > b or a == b respectively. Used by qsort */
static int comp_mystruct(const void *a, const void *b);
/* utility function to print an array of our struct */
static void print_mystruct(const void *start, size_t n);
int main(void)
{
/* some data */
struct MyStruct data[] = {
{ 1, 10 },
{ 5, 50 },
{ 2, 20 },
{ -3, 100 }
};
size_t ndata = sizeof data / sizeof data[0];
/* before sorting */
print_mystruct(data, ndata);
putchar('\n');
/* sort the array now */
qsort(data, ndata, sizeof data[0], comp_mystruct);
/* after sorting */
print_mystruct(data, ndata);
return 0;
}
static void print_mystruct(const void *start, size_t n)
{
size_t i;
const struct MyStruct *s = start;
for (i=0; i < n; ++i) {
printf("% 3d % 3d\n", s[i].iID, s[i].iMyNumber);
}
}
static int comp_mystruct(const void *a, const void *b)
{
const struct MyStruct *sa = a;
const struct MyStruct *sb = b;
if (sa->iID > sb->iID) {
return 1;
} else if (sa->iID < sb->iID) {
return -1;
} else {
return 0;
}
}
The output of the program is:
1 10
5 50
2 20
-3 100
-3 100
1 10
2 20
5 50
The advantage is that qsort()
is standard, and you can use it to sort anything.