473,700 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Questions about qsort( ) to sort pointer to struct.

Hi!

I have questions about qsort( ). Is anyone be willing to help?

I use the following struct:
struct Struct_A{
double value;
...
} *AA, **pAA;

After allocating memory, I have pAA[n], and AA[n].
For all i, 0 <= i < n, pAA[i] = &AA[i] ;

I want to retrieve all the AA[i].value's according to the
value(decending order). So I want to sort.
Instead of sorting the whole AA[n](size_of(struct Struct_A) is very
large),
I use pAA[i] as a handle and sort pAA[i] according to pAA[i]->value.
pAA[0]->value should be the biggest one.

I triied:
qsort( (void **) pAA, n, sizeof(struct Struct_A * ), comp);
and
int comp(const void * row1, const void * row2)

struct Struct_A * Arow1
= (struct Struct_A *) row1;

struct Struct_A * Arow2
= (struct Struct_A *) row2;

if ( Arow1->value < Arow2->value) return (1);
elseif if if ( Arow1->value > Arow2->value) return (-1);
else return(0);
}
The code can run, but not in the way I need.

before sort:
pAA[0]->value = 0.688875
pAA[1]->value = 0.580136
pAA[2]->value = 0.379049
pAA[3]->value = 0.606478
pAA[4]->value = 0.742888
pAA[5]->value = 0.908687
pAA[6]->value = 0.969579
after sort
pAA[0]->value = 0.969579
pAA[1]->value = 0.908687
pAA[2]->value = 0.742888
pAA[3]->value = 0.606478
pAA[4]->value = 0.688875
pAA[5]->value = 0.379049
pAA[6]->value = 0.580136

and the following one works.
int comp(const void * row1, const void * row2)
{

struct Struct_A * Arow1
= *((struct Struct_A **) row1);

struct Struct_A * Arow2
= *((struct Struct_A **) row2);

if ( Arow1->value < Arow2->value) return (1);

else if ( Arow1->value > Arow2->value) return (-1);

else return 0;

}

Why does "*((struct Struct_A **) row1)" work? but not "(struct Struct_A
*) row1"?
To me, Both row1 point to the same location "&AA[i]".
I am confused why the (struct Struct_A *) row1 version can not lead to
the correct result?

Is anyone able to use PLAIN English explain what is the difference?
and why dose the 2nd can not sort by "value"?

A sorting need to swap data.
The first one swap pAA[i] and pAA[j] if necessary.
What data will the (struct Struct_A *) row1 version indeed swap?

Thanks!

Nov 14 '05 #1
4 2810


PCHOME wrote:
Hi!

I have questions about qsort( ). Is anyone be willing to help?

I use the following struct:
struct Struct_A{
double value;
...
} *AA, **pAA;

After allocating memory, I have pAA[n], and AA[n].
For all i, 0 <= i < n, pAA[i] = &AA[i] ;

I want to retrieve all the AA[i].value's according to the
value(decending order). So I want to sort.
Instead of sorting the whole AA[n](size_of(struct Struct_A) is very
large),
I use pAA[i] as a handle and sort pAA[i] according to pAA[i]->value.
pAA[0]->value should be the biggest one.

I triied:
qsort( (void **) pAA, n, sizeof(struct Struct_A * ), comp);
It would be better to use

qsort (pAA, n, sizeof *pAA, comp);

First, the `(void**)pAA' cast is wrong -- you will get
away with it on many machines, but it is wrong nonetheless
and there's no benefit in taking unnecessary risks. The
correct cast would be `(void*)pAA' but even that much is
unnecessary (assuming a prototype for qsort() is in scope,
which it certainly should be). In fact, with the prototype
the compiler will treat your original as equivalent to
`(void*)(void** )pAA'.

Second, `sizeof *pAA' is preferable to your original.
The original you wrote was correct, but `sizeof *pAA' offers
fewer opportunities to make silly errors. The compiler knows
what type `pAA' points to; let the compiler do the work of
figuring out the size.
and
int comp(const void * row1, const void * row2)

struct Struct_A * Arow1
= (struct Struct_A *) row1;
This would be right if you were sorting an array of
`struct Struct_A' objects, but you're not: you're sorting an
array of pointers to such objects. `row1' does not point
to a struct; it points to a pointer to a struct. Here's
what you need:

struct Struct_A * Arow1
= * (struct Struct_A **)row1;

That is: You convert `row1' from `void*' to a pointer to an
element of the array. Then since the array element is itself
a pointer to the ultimate struct, you apply `*' to the converted
array pointer to fetch the struct pointer.

Here's a simple rule: The type of the first argument to
qsort() is the type to which the comparison function's
arguments should be converted, give or take a `const'.
[...]
and the following one works.
int comp(const void * row1, const void * row2)
{

struct Struct_A * Arow1
= *((struct Struct_A **) row1);
Right. The things being sorted are pointers, and comp()
receives pointers to two of those things, hence the double
`**': comp() receives pointers to pointers.
Why does "*((struct Struct_A **) row1)" work? but not "(struct Struct_A
*) row1"?
To me, Both row1 point to the same location "&AA[i]".


No, `row1' points to an element in the `pAA' array and
not to a struct at all. The array element points to a struct
in the `AA' array, but `row1' does not point there.

| | | |
+------+ +-------------+
row1 ---> |pAA[i]----> | AA[j] |
+------+ +-------------+
| | | |
+------+ +-------------+
| | | |
(You say that i==j when the sort begins, but that will not
remain true when qsort() rearranges the `pAA' array.)

--
Er*********@sun .com

Nov 14 '05 #2
PCHOME wrote:

Hi!

I have questions about qsort( ). Is anyone be willing to help?

I use the following struct:
struct Struct_A{
double value;
...
} *AA, **pAA;

After allocating memory, I have pAA[n], and AA[n].
For all i, 0 <= i < n, pAA[i] = &AA[i] ;

I want to retrieve all the AA[i].value's according to the
value(decending order). So I want to sort.
Instead of sorting the whole AA[n](size_of(struct Struct_A) is very
large),
I use pAA[i] as a handle and sort pAA[i] according to pAA[i]->value.
pAA[0]->value should be the biggest one.

I triied:
qsort( (void **) pAA, n, sizeof(struct Struct_A * ), comp);
and
int comp(const void * row1, const void * row2)

struct Struct_A * Arow1
= (struct Struct_A *) row1;

struct Struct_A * Arow2
= (struct Struct_A *) row2;

if ( Arow1->value < Arow2->value) return (1);
elseif if if ( Arow1->value > Arow2->value) return (-1);
else return(0);

}
The code can run, but not in the way I need.

before sort:
pAA[0]->value = 0.688875
pAA[1]->value = 0.580136
pAA[2]->value = 0.379049
pAA[3]->value = 0.606478
pAA[4]->value = 0.742888
pAA[5]->value = 0.908687
pAA[6]->value = 0.969579
after sort
pAA[0]->value = 0.969579
pAA[1]->value = 0.908687
pAA[2]->value = 0.742888
pAA[3]->value = 0.606478
pAA[4]->value = 0.688875
pAA[5]->value = 0.379049
pAA[6]->value = 0.580136

and the following one works.
int comp(const void * row1, const void * row2)
{

struct Struct_A * Arow1
= *((struct Struct_A **) row1);

struct Struct_A * Arow2
= *((struct Struct_A **) row2);

if ( Arow1->value < Arow2->value) return (1);

else if ( Arow1->value > Arow2->value) return (-1);

else return 0;

}

Why does "*((struct Struct_A **) row1)" work?
but not "(struct Struct_A *) row1"?
To me, Both row1 point to the same location "&AA[i]".
I am confused why the (struct Struct_A *) row1 version can not lead to
the correct result?

Is anyone able to use PLAIN English explain what is the difference?
I wish I could.
and why dose the 2nd can not sort by "value"?

A sorting need to swap data.
The first one swap pAA[i] and pAA[j] if necessary.
What data will the (struct Struct_A *) row1 version indeed swap?


/* BEGIN output new.c */

AA[0].value is 0.688875
AA[1].value is 0.580136
AA[2].value is 0.379049
AA[3].value is 0.606478
AA[4].value is 0.742888
AA[5].value is 0.908687
AA[6].value is 0.969579

pAA[0]->value is 0.969579
pAA[1]->value is 0.908687
pAA[2]->value is 0.742888
pAA[3]->value is 0.688875
pAA[4]->value is 0.606478
pAA[5]->value is 0.580136
pAA[6]->value is 0.379049

/* END output new.c */

/* BEGIN new.c */

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

#define NELEM 7

struct Struct_A {
double value;
struct Struct_A *next;
};

int comp(const void *arg1, const void *arg2);

int main(void)
{
struct Struct_A *AA, **pAA;
unsigned index;

AA = malloc(NELEM * sizeof *AA);
pAA = malloc(NELEM * sizeof *pAA);
if (AA == NULL || pAA == NULL) {
exit(EXIT_FAILU RE);
}
AA[0].value = 0.688875;
AA[1].value = 0.580136;
AA[2].value = 0.379049;
AA[3].value = 0.606478;
AA[4].value = 0.742888;
AA[5].value = 0.908687;
AA[6].value = 0.969579;
puts("/* BEGIN output new.c */\n");
for (index = 0; index != NELEM; ++index) {
pAA[index] = AA + index;
printf("AA[%u].value is %f\n", index, AA[index] .value);
}
putchar('\n');
qsort(pAA, NELEM, sizeof *pAA, comp);
for (index = 0; index != NELEM; ++index) {
printf("pAA[%u]->value is %f\n", index, pAA[index]->value);
}
free(AA);
free(pAA);
puts("\n/* END output new.c */");
return 0;
}

int comp(const void *arg1, const void *arg2)
{
double value_1 = (**(struct Struct_A**)arg1 ).value;
double value_2 = (**(struct Struct_A**)arg2 ).value;

return value_1 > value_2 ? -1 : value_1 != value_2;
}

/* END new.c */
--
pete
Nov 14 '05 #3
Nice job!

Nov 15 '05 #4
"I_have_nothing " <dd******@yahoo .com.tw> writes:
Nice job!


What?

Don't assume that your readers have access to the article to which
you're replying. (It appears to have expired on my server.)

If you've been following this newsgroup, you've seen the following
many times:

If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <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.
Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2785
by: cpuracr8 | last post by:
i've been looking through the topics here and i can't quite find one that helps me. i'm trying to sort a struct that contains three arrays using the sort() function. the three arrays are parallel and need to be grouped together when it is sorted. for instance, if i sort the int array by ascending order, i need the name and grade associated with that int array to also move with it. i hope what i said is not too confusing. what am i doing...
1
1440
by: Angus Comber | last post by:
Hello I have a struct with two elements as follows: int nNumber char szName I want to sort szName by nNumber. Eg nNumber might be 1, 3, 6, 2 - and I want to re-sort szName - possibly intro a new struct. What is the easiest way for me to do this?
7
5290
by: Angus Comber | last post by:
Hello Here is my code so far. Is this correct/incorrect/along the right lines/other? #include <stdio.h> #include <string.h> #include <search.h> struct mystruct {
16
16408
by: Gerrit | last post by:
Hello, Is it possible to sort an array with a struct in it? example: I have a struct: public struct mp3file { public int tracknr;
7
1960
by: sarathy | last post by:
Hi, 1. How it that the results for the size of struct1 and struct2 (below) are 4 and 3 # include <stdio.h> struct struct1 { const :16;
5
7812
by: A. Farber | last post by:
Hello, I call readv() and writev() in several spots of a program which I run under Linux, OpenBSD and Cygwin. Since it always the same way (check the return value; then check errno and retry if EAGAIN/EINTR), I've written a wrapper function (full source code on the bottom) to call those functions and just pass the function pointer to it: do { ...
5
1513
by: Chris Saunders | last post by:
Here is the C declaration of a struct from Windows: typedef struct _TXFS_READ_BACKUP_INFORMATION_OUT { union { // // Used to return the required buffer size if return code is STATUS_BUFFER_OVERFLOW //
0
8709
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
8638
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,...
0
9202
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9058
jinu1996
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...
1
8952
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,...
0
5894
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();...
0
4649
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3081
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2018
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.