Hi,
I'm trying to sort structs defined as follows:
struct combinationRec {
float score;
char* name;
};
The number of structs and the length of the "name" field are not known
at compile time.
I've been struggling with this code all afternoon...
I believe I'm sticking to what's explained into the C faq. This is
probably not the case because qsort just crashes on me!
Does anyone have an idea why ?
Matt
/*
* qsort of malloc'ed structs
*/
#include <stdio.h>
#include <stdlib.h>
struct combinationRec {
float score;
char* name;
};
// Score sorting function
int scoreSort(const void *p1, const void *p2) {
struct combinationRec *sp1 = *(struct combinationRec * const *)p1;
struct combinationRec *sp2 = *(struct combinationRec * const *)p2;
if (sp1->score < sp2->score) return -1;
if (sp1->score > sp2->score) {return +1;}
else {return 0;}
}
int main(int argc, char* argv[])
{
combinationRec *allCombination s;
combinationRec *currComb;
int i, j;
int numStructs;
int nameLength;
char letter;
randomize();
numStructs = rand()%15+1;
if ( (allCombination s = (combinationRec *) malloc( sizeof
(combinationRec )*numStructs)) == NULL ) {
printf("Not enough memory to allocate buffer\n");
exit(EXIT_FAILU RE);
}
for (i=0; i<numStructs; i++) {
currComb = &allCombination s[i];
nameLength = rand()%15+1;
if ( (currComb->name = (char *) malloc( sizeof (char)*(
nameLength + 1 ))) == NULL ) {
printf("Not enough memory to allocate buffer\n");
exit(EXIT_FAILU RE);
}
currComb->score = (float) (rand()% 50) / 3.14159;
for (j=0; j<nameLength; j++) {
letter = rand()%26 + 'A';
currComb->name[j] = letter;
}
currComb->name[nameLength] = '\0';
}
// Display structs before sort
printf("Before sort:\n");
for (i=0; i<numStructs; i++) {
printf("struct no. %2i: score=%7.3f name=%s\n",
i,
allCombinations[i].score,
allCombinations[i].name
);
}
printf("Calling qsort\n");
// Sort structs by score
qsort(allCombin ations, numStructs , sizeof( allCombinations[0] ),
scoreSort);
// Show sorted scores
printf("Sorted: \n");
for (i=0; i<numStructs; i++) {
printf("struct no. %2i: score=%7.3f name=%s\n",
i,
allCombinations[i].score,
allCombinations[i].name
);
}
// Cleanup
for (i=0; i<numStructs; ++i) {
free((void *)allCombinatio ns[i].name);
}
free((void *)allCombinatio ns);
// Exit
return 0;
} 5 2766
Bidule wrote: Hi,
I'm trying to sort structs defined as follows:
struct combinationRec { float score; char* name; };
The number of structs and the length of the "name" field are not known at compile time. I've been struggling with this code all afternoon... I believe I'm sticking to what's explained into the C faq. This is probably not the case because qsort just crashes on me!
Does anyone have an idea why ?
Matt /* * qsort of malloc'ed structs */
#include <stdio.h> #include <stdlib.h>
struct combinationRec { float score; char* name; };
// Score sorting function int scoreSort(const void *p1, const void *p2) { struct combinationRec *sp1 = *(struct combinationRec * const *)p1; struct combinationRec *sp2 = *(struct combinationRec * const *)p2;
These lines should read:
const struct combinationRec *sp1 = (const struct combinationRec *)p1;
const struct combinationRec *sp2 = (const struct combinationRec *)p2; if (sp1->score < sp2->score) return -1; if (sp1->score > sp2->score) {return +1;} else {return 0;} } [snip]
// Sort structs by score qsort(allCombin ations, numStructs , sizeof( allCombinations[0] ), scoreSort); [snip]
Bidule wrote: Hi,
I'm trying to sort structs defined as follows:
struct combinationRec { float score;
Why use float rather than double? In general, if you need a floating
point type double should be your default choice unless you have a
specific reason for using something else. After all, floats keep getting
converted to doubles anyway.
char* name; };
The number of structs and the length of the "name" field are not known at compile time. I've been struggling with this code all afternoon... I believe I'm sticking to what's explained into the C faq. This is probably not the case because qsort just crashes on me!
Does anyone have an idea why ?
Well, I've got a few comments on the code, one of which is the reported
problem. The first is that it doesn't compile if fed to a C compiler.
I suspect you have been using a C++ compiler which is a serious mistake
since that is a different language.
/* * qsort of malloc'ed structs */
#include <stdio.h> #include <stdlib.h>
struct combinationRec { float score; char* name; };
// Score sorting function int scoreSort(const void *p1, const void *p2) { struct combinationRec *sp1 = *(struct combinationRec * const *)p1; struct combinationRec *sp2 = *(struct combinationRec * const *)p2;
Don't cast to/from void* pointers, you don't need to if you do it write.
Also you seem not to understand the difference in positions of const and
what it means. In this case a simple:
const struct combinationRec *sp1 = p1;
const struct combinationRec *sp2 = p2;
It's the mess you made of this that is the problem. Look again at the
definition of qsort and the parameters it passes to your comparison
function. Note that I don't have as much indirection as you.
if (sp1->score < sp2->score) return -1; if (sp1->score > sp2->score) {return +1;} else {return 0;} }
int main(int argc, char* argv[]) { combinationRec *allCombination s; combinationRec *currComb;
Both the above lines are errors since C, unlike C++, does not
automatically create type aliases when you define a struct.
struct combinationRec *allCombination s;
struct combinationRec *currComb;
int i, j; int numStructs; int nameLength; char letter;
randomize();
There is no such function as randomise. Perhaps you should look up srand
in your documentation.
numStructs = rand()%15+1; if ( (allCombination s = (combinationRec *) malloc( sizeof (combinationRec )*numStructs)) == NULL ) {
In C you don't need the cast, and in any case you don't have a type
named combinationRec. The cast is ugly and prevents the compiler
prodicing a required diagnistic if you forget to include stdlib.h.
if ( (allCombination s =
malloc( numstructs * sizeof *allCombination s)) == NULL ) {
Note also using sizeof *ptrname, much less likely to make an error that way.
printf("Not enough memory to allocate buffer\n"); exit(EXIT_FAILU RE); }
for (i=0; i<numStructs; i++) { currComb = &allCombination s[i];
nameLength = rand()%15+1;
if ( (currComb->name = (char *) malloc( sizeof (char)*( nameLength + 1 ))) == NULL ) {
sizeof(char) is 1 by *definition*. So so following is fine:
if ( (currComb->name = malloc( nameLength + 1 )) == NULL ) {
printf("Not enough memory to allocate buffer\n"); exit(EXIT_FAILU RE); }
currComb->score = (float) (rand()% 50) / 3.14159; for (j=0; j<nameLength; j++) { letter = rand()%26 + 'A'; currComb->name[j] = letter; } currComb->name[nameLength] = '\0'; }
// Display structs before sort printf("Before sort:\n"); for (i=0; i<numStructs; i++) { printf("struct no. %2i: score=%7.3f name=%s\n", i, allCombinations[i].score, allCombinations[i].name ); }
printf("Calling qsort\n");
// Sort structs by score
// style comments don't exist in the original C standard, they have been
added by the latest standard, but conforming compilers are rare. Also,
they are a bad idea for Usenet posts because they don't survive line
wrapping.
qsort(allCombin ations, numStructs , sizeof( allCombinations[0] ), scoreSort);
// Show sorted scores printf("Sorted: \n"); for (i=0; i<numStructs; i++) { printf("struct no. %2i: score=%7.3f name=%s\n", i, allCombinations[i].score, allCombinations[i].name ); }
// Cleanup for (i=0; i<numStructs; ++i) { free((void *)allCombinatio ns[i].name);
Again, the cast isn't needed in C.
free(allCombina tions[i].name);
} free((void *)allCombinatio ns);
free(allCombina tions);
// Exit
Not a very helpful comment.
return 0; }
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
"Bidule" <to**@truc.co m> wrote in message
news:43******** *************@n ews.free.fr... Hi,
I'm trying to sort structs defined as follows:
struct combinationRec { float score; char* name; };
The number of structs and the length of the "name" field are not known at compile time. I've been struggling with this code all afternoon... I believe I'm sticking to what's explained into the C faq. This is probably not the case because qsort just crashes on me!
Does anyone have an idea why ?
Matt /* * qsort of malloc'ed structs */
#include <stdio.h> #include <stdlib.h>
struct combinationRec { float score; char* name; };
// Score sorting function int scoreSort(const void *p1, const void *p2) { struct combinationRec *sp1 = *(struct combinationRec * const *)p1; struct combinationRec *sp2 = *(struct combinationRec * const *)p2; if (sp1->score < sp2->score) return -1; if (sp1->score > sp2->score) {return +1;} else {return 0;} }
int main(int argc, char* argv[]) { combinationRec *allCombination s; combinationRec *currComb;
int i, j; int numStructs; int nameLength; char letter;
randomize(); numStructs = rand()%15+1; if ( (allCombination s = (combinationRec *) malloc( sizeof (combinationRec )*numStructs)) == NULL ) { printf("Not enough memory to allocate buffer\n"); exit(EXIT_FAILU RE); }
[etc]
There are two ways of doing it:
Plan A: create an array of structs, and sort them in place (actually copying
around the contents)
Plan B: create an array of pointers, and sort the pointers according to the
data they point to
You're basically doing Plan A, but your comparison routine belongs to Plan
B. This is where the confusion has come in
--
RSH
Robert Harris wrote: Bidule wrote: I'm trying to sort structs defined as follows:
struct combinationRec { float score; char* name; };
The number of structs and the length of the "name" field are not known at compile time. I've been struggling with this code all afternoon... I believe I'm sticking to what's explained into the C faq. This is probably not the case because qsort just crashes on me!
/* * qsort of malloc'ed structs */
#include <stdio.h> #include <stdlib.h>
struct combinationRec { float score; char* name; };
// Score sorting function int scoreSort(const void *p1, const void *p2) { struct combinationRec *sp1 = *(struct combinationRec * const *)p1; struct combinationRec *sp2 = *(struct combinationRec * const *)p2;
These lines should read: const struct combinationRec *sp1 = (const struct combinationRec *)p1; const struct combinationRec *sp2 = (const struct combinationRec *)p2;
Please leave blank lines between quotations and your material.
As pointed out by Flash, those lines should read:
const struct combinationRec *sp1 = p1;
const struct combinationRec *sp2 = p2;
Casts are evil, to be avoided, and normally wrong.
--
"The power of the Executive to cast a man into prison without
formulating any charge known to the law, and particularly to
deny him the judgement of his peers, is in the highest degree
odious and is the foundation of all totalitarian government
whether Nazi or Communist." -- W. Churchill, Nov 21, 1943
Flash Gordon a écrit : I believe I'm sticking to what's explained into the C faq. This is probably not the case because qsort just crashes on me!
Does anyone have an idea why ?
Well, I've got a few comments on the code, one of which is the reported problem. The first is that it doesn't compile if fed to a C compiler. I suspect you have been using a C++ compiler which is a serious mistake since that is a different language.
True. And actually, this is a very good piece of advice. When compiling
in pure C mode, I get informative error messages.
Thanks for those who have answered. It works well now.
Matt This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Woodster |
last post by:
I knoew that free is usually paired with malloc and delete is usually
paired with malloc, alloc or similar.
Can I use delete with malloc? The main reason I ask is for using the
strdup function. If I have a char *, I have no real way of knowing
whether that char * had memory allocated for it using new or malloc (as
used by strdup).
Thanks in advance
|
by: Simon Nickerson |
last post by:
I have a function which looks like this:
void rho(matrix_t *out, matrix_t *in)
{
static int firsttime = 1;
static matrix_t *words;
/* ... other variables ... */
if (firsttime) {
firsttime = 0
|
by: dam_fool_2003 |
last post by:
Friends,
cannot we malloc a array?
So, I tried the following code:
int main(void)
{
unsigned int y={1,3,6},i,j;
for(i=0;i<3;i++)
printf("before =%d\n",y);
*y = 7; /* 1*/
|
by: Sushil |
last post by:
Hi Gurus
I've tried to come up with a small logical example of my problem.
The problem is platform specific (MIPS) which I understand should not
be discussed here.
So here goes my example:
Code is doing malloc of variable sizes.
The last byte of malloc.ed memory is written a magic.
|
by: apropo |
last post by:
what is wrong with this code? someone told me there is a BAD practice with
that strlen in the for loop, but i don't get it exactly. Could anyone
explain me in plain english,please?
char *reverse(char *s)
{
int i;
char *r;
if(!s) return NULL;//ERROR
r=calloc(strlen(s)+1,sizeof(char));
| |
by: Gabriel de Dietrich |
last post by:
Hi,
I'm doing my first project on embedding and then extending Python in
an application. The idea is to import a set of C++ plug-ins into Python
and then be able to run a script that uses these plug-ins. Please note
that what I'm importing into Python are the plug-in classes in order to
be able to instanciate as many objects as needed.
As usual, all the plug-ins derive from a base class. But two
important things differ for each...
|
by: Khookie |
last post by:
Hi everyone
I'm not sure whether this is good practice or not, so I thought I'll
ask.
I've got a function that returns a char pointer, which is malloc'ed in
the function itself, as per below code. It's basically a singly
linked list of strings that are concatenated into a big string.
My question is - since you have to know to free it yourself (usage
|
by: Khookie |
last post by:
Hi all
I was wondering whether there was a way to know whether a pointer (in
my case, I'm using a char pointer) has been allocated memory through
malloc or not, thus needing to be freed at a later stage?
BTW, I thought this would be a common question - so either I'm just
plain ignorant (coming from a C# and Python background) or my google
skills need to improve.
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |