473,573 Members | 2,773 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A question about 13.9 from the c faq.

At the following url http://c-faq.com/lib/qsort2.html, they have the
following

Q: Now I'm trying to sort an array of structures with qsort. My
comparison function takes pointers to structures, but the compiler
complains that the function is of the wrong type for qsort. How can I
cast the function pointer to shut off the warning?

A: The conversions must be in the comparison function, which must be
declared as accepting ``generic pointers'' (const void *) as discussed
in question 13.8 above. For a hypothetical little date structure

struct mystruct {
int year, month, day;
};

the comparison function might look like [footnote]

int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
if(sp1->year < sp2->year) return -1;
else if(sp1->year sp2->year) return 1;
else if(sp1->month < sp2->month) return -1;
else if(sp1->month sp2->month) return 1;
else if(sp1->day < sp2->day) return -1;
else if(sp1->day sp2->day) return 1;
else return 0;
}

(The conversions from generic pointers to struct mystruct pointers
happen in the initializations sp1 = p1 and sp2 = p2; the compiler
performs the conversions implicitly since p1 and p2 are void
pointers.)

The question is, why don't you use something like

const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Chad
Dec 1 '07 #1
21 1540
Chad wrote:
struct mystruct {
int year, month, day;
};

the comparison function might look like [footnote]

int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
if(sp1->year < sp2->year) return -1;
else if(sp1->year sp2->year) return 1;
else if(sp1->month < sp2->month) return -1;
else if(sp1->month sp2->month) return 1;
else if(sp1->day < sp2->day) return -1;
else if(sp1->day sp2->day) return 1;
else return 0;
}

The question is, why don't you use something like

const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
The initializer would have the wrong type and value. You want to assign
the pointer value, not the address of it.

--
Thad
Dec 1 '07 #2
In article
<0e************ *************** *******@a39g200 0pre.googlegrou ps.com>,
Chad <cd*****@gmail. comwrote:
At the following url http://c-faq.com/lib/qsort2.html, they have the
following

Q: Now I'm trying to sort an array of structures with qsort. My
comparison function takes pointers to structures, but the compiler
complains that the function is of the wrong type for qsort. How can I
cast the function pointer to shut off the warning?

A: The conversions must be in the comparison function, which must be
declared as accepting ``generic pointers'' (const void *) as discussed
in question 13.8 above. For a hypothetical little date structure

struct mystruct {
int year, month, day;
};

the comparison function might look like [footnote]

int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
if(sp1->year < sp2->year) return -1;
else if(sp1->year sp2->year) return 1;
else if(sp1->month < sp2->month) return -1;
else if(sp1->month sp2->month) return 1;
else if(sp1->day < sp2->day) return -1;
else if(sp1->day sp2->day) return 1;
else return 0;
}

(The conversions from generic pointers to struct mystruct pointers
happen in the initializations sp1 = p1 and sp2 = p2; the compiler
performs the conversions implicitly since p1 and p2 are void
pointers.)

The question is, why don't you use something like

const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Because:

&p1 == the address of the variable (parameter, actually) p1

p1 == the variable holding the address of the struct under comparison

*p1 == the struct under comparison

Assuming p1 contains the (randomly chosen) address 5, and assuming p1 is
located in memory at (randomly chosen) location 27, and that the "..."
is replaced by the "const struct mystruct *" as shown above, the
following would be true:

assignment result
....sp1 = &p1 sp now holds 27 (the address of p1)
....sp1 = p1 sp now holds 5 (the contents of p1)
....sp1 = *p1 sp now holds <whatever value is found at location 5>

BUT...
Since p1 is a function parameter, rather than an actual variable, I
believe trying to take its address will result in undefined behavior.
(unless special steps are taken to make things happen differently,
parameters are usually passed on the stack, which makes taking their
address either impossible, or pointless, because for practical purposes,
they don't really HAVE an address to take.)

--
Don Bruder - da****@sonic.ne t - If your "From:" address isn't on my whitelist,
or the subject of the message doesn't contain the exact text "PopperAndShado w"
somewhere, any message sent to this address will go in the garbage without my
ever knowing it arrived. Sorry... <http://www.sonic.net/~dakiddfor more info
Dec 1 '07 #3
Chad wrote:
[... sorting arrays of structs with qsort() ...]

struct mystruct {
int year, month, day;
};

the comparison function might look like [footnote]

int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
[...]

The question is, why don't you use something like

const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Why don't you try it, and see what happens?

To understand why <<spoiler alert>the compiler complains,
ask yourself: What is the type of `&p1'? And what does `&p1'
point to? And to understand the FAQ's code, ask yourself:
What does `p1' point to?

--
Eric Sosman
es*****@ieee-dot-org.invalid
Dec 1 '07 #4
Don Bruder wrote:
....
Since p1 is a function parameter, rather than an actual variable, I
believe trying to take its address will result in undefined behavior.
A function parameter is an actual variable, and it's perfectly legal to
take its address. The only problem is that it's the wrong address, in
this context.
(unless special steps are taken to make things happen differently,
parameters are usually passed on the stack, which makes taking their
address either impossible, or pointless, because for practical purposes,
they don't really HAVE an address to take.)
On the machines where I've had to be familiar with such details, the
stack was a piece of memory that served a different purpose from the
heap and other pieces of memory, but was just as addressable as any of
those other pieces. If an implementation used something for parameter
passing for which that wasn't true (such as registers), it must copy the
values out of the registers into addressable memory, at least if the
code ever actually takes the address of the parameter.
Dec 1 '07 #5
On Dec 1, 12:58 pm, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
Chad wrote:
[... sorting arrays of structs with qsort() ...]
struct mystruct {
int year, month, day;
};
the comparison function might look like [footnote]
int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
[...]
The question is, why don't you use something like
const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;

Why don't you try it, and see what happens?

To understand why <<spoiler alert>the compiler complains,
ask yourself: What is the type of `&p1'? And what does `&p1'
point to? And to understand the FAQ's code, ask yourself:
What does `p1' point to?

--
Eric Sosman
esos...@ieee-dot-org.invalid

Maybe this is lack of experience or maybe it's because I will still
once in a while get this burning sensation when I try to think, but it
appears that p1 points to thing.

Dec 1 '07 #6
James wrote:
) On the machines where I've had to be familiar with such details, the
) stack was a piece of memory that served a different purpose from the
) heap and other pieces of memory, but was just as addressable as any of
) those other pieces. If an implementation used something for parameter
) passing for which that wasn't true (such as registers), it must copy the
) values out of the registers into addressable memory, at least if the
) code ever actually takes the address of the parameter.

Doesn't the standard allow an implementation that has a pointer type
which can point to registers as well as memory ? I could imagine having
some kind of 'fat' pointer type with a flag that indicates 'this is a
pointer to register X'.
SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Dec 1 '07 #7
In article <Iek4j.400$gi7. 54@trnddc04>,
James Kuyper <ja*********@ve rizon.netwrote:
Don Bruder wrote:
...
Since p1 is a function parameter, rather than an actual variable, I
believe trying to take its address will result in undefined behavior.

A function parameter is an actual variable, and it's perfectly legal to
take its address.
OK, then I've been operating under a misconception for a while. While
they BEHAVE as variables, I've always been under the impression that
they "weren't really" due to the passing mechanism.
The only problem is that it's the wrong address, in
this context.
Right. The comparison would be against who-knows-what, but whatever that
turned out to be, it wouldn't be the desired data.

--
Don Bruder - da****@sonic.ne t - If your "From:" address isn't on my whitelist,
or the subject of the message doesn't contain the exact text "PopperAndShado w"
somewhere, any message sent to this address will go in the garbage without my
ever knowing it arrived. Sorry... <http://www.sonic.net/~dakiddfor more info
Dec 1 '07 #8
Chad wrote:
On Dec 1, 12:58 pm, Eric Sosman <esos...@ieee-dot-org.invalidwrot e:
>Chad wrote:
>>[... sorting arrays of structs with qsort() ...]
struct mystruct {
int year, month, day;
};
the comparison function might look like [footnote]
int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
[...]
The question is, why don't you use something like
const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Why don't you try it, and see what happens?

To understand why <<spoiler alert>the compiler complains,
ask yourself: What is the type of `&p1'? And what does `&p1'
point to? And to understand the FAQ's code, ask yourself:
What does `p1' point to?

Maybe this is lack of experience or maybe it's because I will still
once in a while get this burning sensation when I try to think, but it
appears that p1 points to thing.
Right: `p1' points to one of the things in the array
being sorted, that is, to a `struct mystruct' instance. The
only problem is the type: `p1' is a `void*', but to get at
the struct elements you need a `struct mystruct*'. Hence
the conversion to `sp1'.

How did you make out with the other two questions? (And
did you try the experiment I suggested, or did you just accept
my spoiler as Gospel? It's flattering when people believe
what I say, but it's not always their wisest course ...)

--
Eric Sosman
es*****@ieee-dot-org.invalid
Dec 1 '07 #9
Chad <cd*****@gmail. comwrites:
At the following url http://c-faq.com/lib/qsort2.html, they have the
following

Q: Now I'm trying to sort an array of structures with qsort. My
comparison function takes pointers to structures, but the compiler
complains that the function is of the wrong type for qsort. How can I
cast the function pointer to shut off the warning?

A: The conversions must be in the comparison function, which must be
declared as accepting ``generic pointers'' (const void *) as discussed
in question 13.8 above. For a hypothetical little date structure

struct mystruct {
int year, month, day;
};

the comparison function might look like [footnote]

int mystructcmp(con st void *p1, const void *p2)
{
const struct mystruct *sp1 = p1;
const struct mystruct *sp2 = p2;
if(sp1->year < sp2->year) return -1;
else if(sp1->year sp2->year) return 1;
else if(sp1->month < sp2->month) return -1;
else if(sp1->month sp2->month) return 1;
else if(sp1->day < sp2->day) return -1;
else if(sp1->day sp2->day) return 1;
else return 0;
}

(The conversions from generic pointers to struct mystruct pointers
happen in the initializations sp1 = p1 and sp2 = p2; the compiler
performs the conversions implicitly since p1 and p2 are void
pointers.)

The question is, why don't you use something like

const struct mystruct *sp1 = &p1;
const struct mystruct *sp2 = &p2;
Um, because it's illegal (a constraint violation), and even if it
weren't it wouldn't work.

p1 is a parameter (a local object) of type void* (I'm ignoring the
const qualifier). When converted to type ``struct mystruct*'',
assuming the caller has passed the right arguments, it points to an
object of type ``struct mystruct''.

You propose instead to use ``&p1'', i.e., the *address* of p1. This
is the address of a pointer object, and is of type void**.

The question is, why would you want to use ``&p1'' when ``p1'' is
correct?

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 1 '07 #10

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

Similar topics

1
2830
by: eScrewDotCom | last post by:
eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew story is so funny that eScrew will have to take break from time to time because eScrew needs some rest from laughing. Oh boy, here it comes......
220
18900
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it...
8
2454
by: eScrewDotCom | last post by:
eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew story is so funny that eScrew will have to take break from time to time because eScrew needs some rest from laughing. Oh boy, here it comes......
77
5657
by: nospam | last post by:
Reasons for a 3-tier achitecture for the WEB? (NOTE: I said, WEB, NOT WINDOWS. DON'T shoot your mouth off if you don't understand the difference.) I hear only one reason and that's to switch a database from SQL Server to Oracle or DB2 or vice versa... and that's it.... And a lot of these enterprises don't need it as they already know what...
125
14608
by: Sarah Tanembaum | last post by:
Beside its an opensource and supported by community, what's the fundamental differences between PostgreSQL and those high-price commercial database (and some are bloated such as Oracle) from software giant such as Microsoft SQL Server, Oracle, and Sybase? Is PostgreSQL reliable enough to be used for high-end commercial application? Thanks
5
2987
by: eScrewDotCom | last post by:
www.eScrew.com eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew story is so funny that eScrew will have to take break from time to time because eScrew needs some rest from laughing. Oh boy,...
81
7246
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
0
2438
by: eScrewDotCom | last post by:
eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew story is so funny that eScrew will have to take break from time to time because eScrew needs some rest from laughing. Oh boy, here it comes......
7
3132
by: Edward Yang | last post by:
A few days ago I started a thread "I think C# is forcing us to write more (redundant) code" and got many replies (more than what I had expected). But after reading all the replies I think my question about local variable initialization is still not solved. And some of the replies forked into talking about out parameters. And the thread is...
0
7784
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...
0
8033
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. ...
0
8206
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...
1
7796
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...
0
6426
agi2029
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...
0
5294
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...
0
3734
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...
1
2224
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
0
1044
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...

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.