473,385 Members | 1,901 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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]))
++count;

for (i = 0; i < count; ++i)
puts(lines[i]);
}

Thanks.
Nov 13 '05 #1
3 6368
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]))
++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

http://www.eskimo.com/~scs/C-faq/s12.html

.... 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
zero.

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)
puts(lines[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().
}

Thanks.


You're welcome. Good luck!

--
Er*********@sun.com
Nov 13 '05 #2
"Eric Sosman" <Er*********@sun.com> wrote in message
news:3F***************@sun.com...
SilverWolf wrote:
char lines[100][100]; for (i = 0; i < count; ++i)
puts(lines[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
later.
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.

$.02,
-Mike
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.

<snip>

--
Richard Heathfield : bi****@eton.powernet.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

7
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)) ...
16
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...
4
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...
0
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...
7
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...
1
KevinADC
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...
2
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. ...
5
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...
5
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...

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.