Question
I have a sorted struct of IPs where I need to get the number of unique IPs, for some reason the way I'm doing it, is giving me a "0" as a result. Which in this case there should be 12 unique ips.
The struct array containing the following elements:
195.55.121.242
212.80.168.34
65.55.106.114
65.55.207.30
65.55.207.95
65.55.230.237
66.249.68.16
66.249.68.16
66.249.68.16
67.195.37.172
67.195.37.172
67.218.116.162
80.59.182.176
80.59.182.176
83.213.81.220
83.213.81.220
83.43.21.186
83.43.21.186
Code:
typedef struct {
char *ip;
}thestruct;
qsort(mystruct, 18, sizeof(thestruct*), cmpme);
int un = 0;
for (i=0; i<18; i++) {
if (strcmp(mystruct[i++]->ip,mystruct[i]->ip)!=0) {
un++;
}
}
By doing a simple gets-strcmp with only one element (ip) I get that both strings are equal. Which tells me that strcmp is treating it as a string.
I'm not quite sure what I am missing.
Any help will be appreciate it.
Thanks
Solution
Look carefully at this line:
if (strcmp(mystruct[i++]->ip,mystruct[i]->ip)!=0)
You're comparing index i
to index i
(which are equal, since they're the same) and then incrementing i
. (Actually, this is undefined behavior, since you're modifying i
and reading it more than once before a sequence point).
You really want to do this:
if (strcmp(mystruct[i + 1]->ip,mystruct[i]->ip)!=0)
to compare index i+1
to index i
without touching i
, since i
is incremented in the for
loop. Also, i
should only loop from 0 to 17, not 0 to 18, since you don't want to read past the end of the array.
OTHER TIPS
Don't read and modify the same variable in the same statement. That's undefined behaviour!
Try
for (i=0; i<18; i++) {
if (strcmp(mystruct[i+1]->ip,mystruct[i]->ip)!=0) {
i++;
un++;
}
}