Alastair
Alastair

Reputation: 55

while (*next != NULL) loop not exiting when pointer is NULL

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);

Upvotes: 3

Views: 7142

Answers (3)

Saisujithreddy
Saisujithreddy

Reputation: 92

%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

Upvotes: -1

Christoph
Christoph

Reputation: 169823

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);

Upvotes: 0

Morpfh
Morpfh

Reputation: 4093

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);

Upvotes: 4

Related Questions