请有人帮我解决这个问题,以下C代码中的while循环在*next == NULL时似乎无法退出,并尝试使用坏指针调用strlen(*next)在Visual Studio 2010 Express中。我已经尝试了所有我能想到的方法但都无济于事。该代码试图在字符串数组中查找最短和最长的字符串。
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
的值永远不会达到NULL
,但是您却假定它会。请检查您的假设。 - Greg Hewgill