sort of list of pointers

M

MisterE

// Is any of this not portable correct etc?
#include <stdlib.h>

typedef struct b
{
int f;
} B;

//Should pointers to pointers be avoided or nothing wrong with this:
int compare( const void *arg1, const void *arg2 )
{
B **b1;
B **b2;
b1 = (B **)arg1;
b2 = (B **)arg2;
//And are there any reasons to use 1 of these lines over the other:
return ((**b1).f - (**b2).f);
//return (*b1)->f - (*b2)->f;
}

int main (int argc, char *argv[])
{
B **list;
int j = 100;
list = malloc(sizeof(B *)*j);
if (list == NULL) return -1;
while(j)
{
j--;
list[j] = malloc(sizeof(B));
if (list[j] == NULL) return -2;
list[j]->f = j;
}
qsort(list,100,sizeof(B *),compare);
return 0;
}
 
B

Barry Schwarz

// Is any of this not portable correct etc?

// comments are not portable unless you are restricting yourself to
C99 systems.
#include <stdlib.h>

typedef struct b
{
int f;
} B;

//Should pointers to pointers be avoided or nothing wrong with this:

When sorting pointers it is almost impossible to avoid them.

Why should any feature of the language be avoided?
int compare( const void *arg1, const void *arg2 )
{
B **b1;
B **b2;
b1 = (B **)arg1;
b2 = (B **)arg2;
//And are there any reasons to use 1 of these lines over the other:
return ((**b1).f - (**b2).f);
//return (*b1)->f - (*b2)->f;

Either can overflow. You might want to consider using comparisons
(possibly with the conditional operator).
}

int main (int argc, char *argv[])
{
B **list;
int j = 100;
list = malloc(sizeof(B *)*j);
if (list == NULL) return -1;

EXIT_FAILURE, EXIT_SUCCESS, and 0 are the only portable return values
from main.
while(j)
{
j--;
list[j] = malloc(sizeof(B));
if (list[j] == NULL) return -2;
list[j]->f = j;
}
qsort(list,100,sizeof(B *),compare);
return 0;
}
 
I

Ian Collins

pete said:
/* BEGIN new.c */

#include <stdlib.h>
#include <stdio.h>

#define J_INIT 100

typedef struct b {
int f;
} B;

int compare( const void *arg1, const void *arg2 )
{
B **b1 = (B **)arg1;
B **b2 = (B **)arg2;

return (*b2) -> f > (*b1) -> f ? -1
: (*b2) -> f != (*b1) -> f;

I do hate comparisons where one has to ponder what's going on. Why not
something like

int compare( const void *arg1, const void *arg2 )
{
/* Do the messy stuff in one place.
*/
int lhs = (*(const B**)(arg1))->f;
int rhs = (*(const B**)(arg2))->f;

return lhs == rhs ? 0 : lhs > rhs ? 1 : -1;
}

or even;

if (i > j) return 1;
if (i < j) return -1;
return (0);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top