While (* next! = NULL) loop not exiting when pointer is NULL
Please help me with this problem, the while loop in the following C code doesn't seem to end when * next == NULL and tries to call strlen (* next) with a bad ptr in Visual Studio 2010 Express.I tried everything I could come up with no result. 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);
+3
source to share
3 answers
You must change
*current++;
*next++;
to
current++;
next++;
Both increments are ok, but the first also has a reversal / return value 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 are trying to print a character using a formatted string.
This should work:
printf("shortest string: %s\n", shortest);
printf("longest string: %s\n", longest);
+4
source to share