Please can someone help me with this problem, the while loop in the following C code doesn't seem to exit when *next == NULL and tries to call strlen(*next) with a bad ptr in Visual Studio 2010 Express. I've tried everything I can think of to no avail. The code tries to find the shortest and longest strings in an array of strings.
char *stringsInArray[] = {"green mats", "cat", "sat", "on", "the", "green mat", NULL};
char *shortest, *longest, **current, **next, **end;
current = stringsInArray;
next = stringsInArray + 1;
shortest = stringsInArray[0];
longest = stringsInArray[0];
while (*next != NULL)
{
if (strlen(*current) < strlen(*next))
{
if (strlen(shortest) > strlen(*next))
shortest = *next;
if (strlen(*current) < strlen(shortest))
shortest = *current;
if (strlen(*next) > strlen(longest))
longest = *next;
}
else
if (strlen(*current) > strlen(*next))
{
if (strlen(*current) > strlen(longest))
longest = *current;
if (strlen(*next) < strlen(shortest))
shortest = *next;
}
else // strlen(*stringsInArray) == strlen(*next)
{
// do nothing
}
*current++;
*next++;
}
printf("shortest string: %s\n",*shortest);
printf("longest string: %s\n",*longest);
*next
never reaches NULL
, but you assumed it did. Check your assumptions - Greg Hewgill 2012-04-05 19:09
You ought to change
*current++;
*next++;
to
current++;
next++;
Both increment ok, but the former also dereference / return value of current
and next
; which is not needed.
Your problem, however is this:
printf("shortest string: %s\n", *shortest);
printf("longest string: %s\n", *longest);
Here you try to print a character using string as format.
This should work:
printf("shortest string: %s\n", shortest);
printf("longest string: %s\n", longest);
**end
which not is in use. Perhaps this one was part of the fail. - Anyhow: I'm on linux and not able to test VS. But take notice and read warnings carefully (should appear at bottom of VS-gui). Also increase warning level to max - Morpfh 2012-04-05 20:17
The code actually works as expected - you just need to change
printf("shortest string: %s\n",*shortest);
printf("longest string: %s\n",*longest);
to
printf("shortest string: %s\n",shortest);
printf("longest string: %s\n",longest);
gcc -O0
and gcc -O3
and got different results - there may be another problem that I've missed though - have now deleted my answer and comments - Paul R 2012-04-05 19:37
%s expects a pointer to char i.e., char *. Hence it has to be shortest and longest which are pointers instead of *shortest and *longest which are the values at pointer locations