【问题标题】:Reversing words in a sentence using pointers using c使用 c 使用指针反转句子中的单词
【发布时间】:2014-04-16 17:14:53
【问题描述】:

我正在编写一个程序,其中有一个反转字符串中每个单词的函数。当我调用该函数时,它会将指针传递给源字符串,然后将指针返回到修改后的字符串。

输入:为什么总是我? 输出:yhW syawla ?em

但由于某种原因,它不起作用。没有错误。逻辑对我来说似乎很好(我对c不太好,顺便说一句) 这是我的代码:

char *reverse_words(char *source_string)
{
    char *startW, *endW;
    startW = source_string;

    while(*startW != '\0')
    {
        while(*startW == ' ')
        startW++;       //Skip multiple spaces in the beginning

        endW = startW;
        while(*endW != ' ' || *endW != '\0')
        endW++;

        char *_start = startW;
        char *_end = endW - 1;
        char temp;

        while(_end > _start)
        {
            temp = *_start;
            *_start++ = *_end;
            *_end++ = temp;
        }

        startW = endW;
    }

    return source_string;
}

void main() {
    char *s;
    s = malloc(256);
    gets(s);
    printf("%s\n", s);
    char *r = reverse_words(s);
    printf("\nReversed String : %s",r);
    free(s);
    free(r);
}

另外,我正在使用代码块 IDE。在我输入我的字符串后,它会打印回来(main 中的 scanf 和 printf),然后程序停止工作。

任何帮助将不胜感激。

【问题讨论】:

  • 首先,rev=source_string 只是复制引用而不是实际字符串
  • 阅读此内容:ericlippert.com/2014/03/05/how-to-debug-small-programs,然后尝试提出更具体、更有针对性的问题。 “我不知道如何调试我编写的程序”不是一个可以回答的问题,也不是为您进行调试的服务。

标签: c pointers


【解决方案1】:

首先,

    while(*endW != ' ' || *endW != '\0')

是一个无限循环,试试这个吧:

    while(*endW != ' ' && *endW != '\0')

第二,

        *_end++ = temp;

应该是这样的:

        *_end-- = temp;

【讨论】:

    【解决方案2】:

    在最里面的while(_end > _start) 循环中,您同时递增_start_end。所以条件永远不会变成假的。 (好吧,直到_end 溢出。)

    我建议弄清楚如何在 IDE 中进行逐步调试。这样你就可以很容易地理解在这种情况下到底出了什么问题,而无需在脑海中模拟执行。

    【讨论】:

      【解决方案3】:
      #include <stdio.h>
      #include <stdlib.h>
      
      char *reverse_words(const char *source_string){
          const char *startW, *endW;
          char *p, *rev = malloc(256);
          startW = source_string;
          p = rev;
      
          while(*startW != '\0'){
              while(*startW == ' ')
                  *p++ = *startW++;
              if(!*startW)
                  break;
      
              endW = startW;
              while(*endW != ' ' && *endW != '\0')
                  endW++;
              const char *endW2 = endW;
              do{
                  *p++ = *--endW;
              }while(startW!=endW);
              startW = endW2;
          }
          *p = '\0';
          return rev;
      }
      
      int main() {
          char s[256];
          scanf("%255[^\n]", s);
          printf("%s,\n", s);
          char *r = reverse_words(s);
          printf("\nReversed String : %s.", r);
          free(r);
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 2016-11-22
        相关资源
        最近更新 更多