473,563 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting and shuffling array

I need some help with sorting and shuffling array of strings. I can't
seem to get qsort working, and I don't even know how to start to shuffle
the array. Here is what I have for now:

#include <stdio.h>

void main(void)
char lines[100][100];
int count = 0, i;

while (gets(lines[count]))

for (i = 0; i < count; ++i)

Nov 13 '05 #1
3 6393
SilverWolf wrote:

I need some help with sorting and shuffling array of strings. I can't
seem to get qsort working, and I don't even know how to start to shuffle
the array. Here is what I have for now:
Not much, but it already has three errors, two of them
quite serious. I'll point them out and provide some hints
about how to fill in the rest -- hints only, because this
has a homework-y whiff to it ...

By the way, I'm not going to address the "shuffling"
question until you explain more clearly what you want to
do, and how you're going to decide whether an array is
"shuffled" or "unshuffled ." For now, sorting only!
#include <stdio.h>
Since you want to sort, you'll probably want to use the
qsort() library function. And since the things to be sorted
are strings, you'll probably want to use the strcmp() function
to compare them. If so, include the appropriate headers:

#include <stdlib.h>
#include <string.h>
void main(void)
(Sigh.) For the INT_MAX'th time: main() returns an `int'
to indicate whether the program completed successfully or
otherwise. Read all about it in your favorite C reference --
but if that reference advocates `void main', get a different
reference. Use the pages of the old one while seated in the
smallest room of your house, in such a way that they wind up
behind you.
char lines[100][100];
int count = 0, i;

while (gets(lines[count]))
Two serious errors in two lines. The first is that you
are using the deadly gets() function; see Question 12.23 in
the comp.lang.c Frequently Asked Questions (FAQ) list


.... to learn why you should never do this.

The second error is similar in nature to the first, except
that you've written it yourself instead of inheriting it from
the library: What happens if somebody feeds 315 strings into
this program? You blindly try to fill a 100-place array with
215 more strings than it can hold, and there's no telling what
might happen. Most likely, the "overflow" strings will stomp
all over some other piece of memory and your program will crash,
but that's only if you're lucky.

Okay: If you've made it this far, you have an array holding
`count' 100-character strings. You can now use qsort() to put
them into order, like this:

qsort (lines, count, sizeof lines[0], compare_func);

The first argument is the array to be sorted, the second is the
number of strings in the array, the third is the number of bytes
in each string, and the last is the name of a comparison function.

"A comparison function," you ask? Yes: qsort() rearranges
the array in accordance with an ordering relation that you
define, and the way you define it is by providing a function.
This function accepts pointers to two array elements and decides
what their order should be in the sorted array. If the first
must precede the second, the function returns a negative value.
If the second must precede the first, the function returns a
positive value. If their order doesn't matter (they are "equal"
in all respects that are important to you), the function returns

Question 13.8 in the FAQ illustrates how to write such a
comparison function, *but* note that it is sorting an array of
pointers to strings, not an array of strings themselves as in
your case. The FAQ's code won't work for you -- in fact, the
FAQ's question wouldn't even arise for you! Ponder it anyhow,
to get an idea of how comparison functions work.
for (i = 0; i < count; ++i)
Since main() returns an `int' (see above), you need a `return'
statement here. Any `int' at all will do, but you may confuse
your operating environment if you return some nonsensical status.
Three values that are guaranteed to make as much sense as possible
to the environment are zero (indicating success), EXIT_SUCCESS
(also indicating success, possibly in a different way), and
EXIT_FAILURE (indicating failure). The latter two values are
defined in <stdlib.h>, which you've already included in order to
use qsort().


You're welcome. Good luck!

Er*********@sun .com
Nov 13 '05 #2
"Eric Sosman" <Er*********@su n.com> wrote in message
news:3F******** *******@sun.com ...
SilverWolf wrote:
char lines[100][100]; for (i = 0; i < count; ++i)

qsort (lines, count, sizeof lines[0], compare_func);

The first argument is the array to be sorted, the second is the
number of strings in the array, the third is the number of bytes
in each string,

While this is indeed the correct argument to use,
sizeof lines[0] will be 100, the size of each ("second
dimension") element of the array 'lines'. I'd say that
the number of bytes in each *string*, is determined by
strlen(lines[i]). I know you're probably trying to keep
things "simple", but imo this could lead to confusion
To "SiverWolf" : 'qsort()' needs to be told the size
is 100, since it cannot know how many of the 100 bytes
are actually part of the string (anything after the
first '\0' character is not part of the string).

Other than that, an excellent reply, Eric.

Nov 13 '05 #3
SilverWolf wrote:
I need some help with sorting and shuffling array of strings.
Don't try to run before you can walk. You have the wrong return type for
main(), and you are using the broken gets() function.
I can't
seem to get qsort working,
qsort already works just fine. You just don't know how to drive it. And it
doesn't make sense to try to drive qsort correctly when your knowledge of
much more basic stuff, such as main and gets, is so flawed. Build only on
truth, and your understanding of the harder stuff will be much clearer.
and I don't even know how to start to shuffle
the array.

If you had been paying attention eight or nine hours ago in IRC, you would
have seen how to do the array shuffle. Array shuffling is dealt with in FAQ
13.19 in the book. I haven't checked the online version.


Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #4

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

Similar topics

by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
by: glowfire | last post by:
Please, somebody help me with this program! We have a deck of 52 cards and we shuffle the deck by choosing a random card out of the deck placing it back in the deck at some random place. Repeat it 500 times and then consider the deck shuffled. Choose a hand of 5 cards from the top of the deck. Count the number of hands which have...
by: bg_ie | last post by:
Hi, I have an array as follows - var MultiArray = new Array(2); MultiArray = new Array(num); MultiArray = new Array(num); I've tried randomizing this array using the following but its obviously wrong -
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another way... here is my code on how I did it to help anyone starting out get an idea of how to use virtual mode in ..NET 2.0 Imports...
by: Kamal | last post by:
Hello all, I have a very simple html table with collapsible rows and sorting capabilities. The collapsible row is hidden with css rule (display:none). When one clicks in the left of the expandable row, the hidden row is made visible with css. The problem is when i sort the rows, the hidden rows get sorted as well which i don't want and want...
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar methods or syntax to a less experienced perl coder. I will post links to online resources you can read if necessary. Experienced perl coders might find...
by: Peter Duniho | last post by:
On Wed, 28 May 2008 06:23:35 -0700, Adam Sandler <corn29@excite.comwrote: No, it can't. Not unless it had duplicates to start with. Personally, I wouldn't bother with such a contrived loop. Something simpler is fine: for (int i = 0; i < a.Length; i++) {
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The search algorithms that can be used are Linear Search and Binary Search. The sorting algorithms are bubble, selection and Insertion sort. First, the user...
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums there are, it crashes. There are currently 6 columns, and I only want 4. How do I remove the last two (discount and date)? Here is a link:...
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...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
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...
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...
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...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
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...

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.