Re: Sorting Array of Structures



Richard Heathfield <invalid@xxxxxxxxxxxxxxx> writes:
Allie said:

To Richard: qsort( book, n, sizeof( book[0] ), comptitle ); gives me
the right output. You had written qsort( book, sizeof( book ) / sizeof
(book[0] ), sizeof book[0], comptitle );

What I wrote was based on the information you gave me. If you gave me the
wrong information, that is your lookout, not mine.

Quoting the article that started this thread:

] How would I go about sorting this structure by title?
]
] typedef struct {
] char author[40];
] char title[40];
] char code[4];
] int hold;
] int loan;
] } LIBRARY;
]
] LIBRARY book[N];
]
]
] This is what I've written:
]
] void sortbytitle( LIBRARY *b, int n ) { /* n = number of books in stock
] */
] LIBRARY temp[N];
] int i;
]
] for( i = 0; i < n; i++ ) {
] if( strcmp( b[i].title, b[i + 1].title ) > 0 ) {
] temp[i] = b[i];
] b[i] = b[i + 1];
] b[i + 1] = temp[i];
] }
] }
]
] return;
] }

The code is wrong in a number of ways (the sorting algorithm doesn't
work, and the use of an array of temporaries is unnecessary), but
given the declarations of book (an array of N LIBRARY objects) and
sortbytitle (a function taking a pointer to LIBRARY and an int n,
"number of books in stock"), it seemed reasonably obvious from the
beginning that N is the total size of the array and n is the number of
array elements that contain valid values.

The use of both N and n as identifiers is legal, but confusingly poor
style.

Richard, I'm not surprised that you missed this, but it was there.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • Re: [Lit.] Buffer overruns
    ... sizeof isn't int nor even necessarily unsigned int (which ... assume that every sizeof result is immediately cast to int. ... the address of an array is a pointer to an array ...
    (sci.crypt)
  • Re: #define....
    ... > sizeof gets the number of items in an array, ... The sizeof statement gives a size of its argument in bytes. ... int j = something; ... After the precompiler stops its work, ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: Sorting Array of Structures
    ... You had written qsort(book, sizeof(book) / sizeof ... Richard's sizeof/ sizeof(bookassumes you want to sort the ... entire array; apparently you just want to sort the first n entries. ...
    (comp.lang.c)