我看到了一个非常有趣的代码来反转字符串,
但我在这里不明白:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void Reverse(char *s);

int main()
{
    char *s=NULL;
    s=(char *)malloc(sizeof(char *));
    gets(s);
    Reverse(s);
    puts(s);
    return 0;
}

void Reverse(char *s)
{
    char *end=s;
    char tmp;
    if (s)
    {
        while (*end)
        {
            ++end;
        }
        --end;
        while (s<end)  ??
        {
            tmp=*s;
            *s++=*end;
            *end--=tmp;
        }
    }
}


我看到该程序尝试通过使用end = s同时更改两个字符串来对同一字符串进行处理,但是'*'行是什么意思:while(s<end)在这里是什么意思?

我使用gdb并发现,当我们输入asdfgh时,当* s是fdsa且* end是fds时,这不再成立了,这行如何控制程序?

我只想知道什么'??'线均值

非常感谢 !

最佳答案

C中的字符串以\0字符终止,该字符的整数值为0。因此,这是一个错误的值。

通过使用while(*end),您可以检查end是否指向给定字符串的终止字符。如果未指向末尾,则将其进一步移动(++end)。为了确保指针有效,您可以在此之后向后移动“光标”。

while(s < end)现在将移动,检查s是否比end进一步转发。如果没有,那么您将交换两个“光标”的值。 end将移向s,反之亦然。这样,您将反转字符串。

您调试的输出是gdbs解释的结果。它将end解释为字符串,而不是单个字符。调试时看看*end

请注意,您的malloc是完全错误的。您必须为字符串分配足够的内存,例如s = malloc(500*sizeof(char));。使用fgets代替,您可以在其中指定要读取的最大字符数。不要忘记释放分配的所有内存:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 500

void Reverse(char *s);

int main()
{
    char* s = malloc(BUFFER_SIZE * sizeof(char));
    fgets(s,BUFFER_SIZE,stdin);
    Reverse(s);
    puts(s);
    free(s);
    return 0;
}

void Reverse(char *s)
{
    char* end=s;
    char tmp;
    if(s)
    {
        while (*end)
        {
            ++end;
        }
        --end;
        while (s<end)
        {
            tmp=*s;
            *s++=*end;
            *end--=tmp;
        }
    }
}

关于c - 与字符串比较在这里意味着什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9916061/

10-11 22:59
查看更多