使用指针反转字符串的C代码

Rit*_*esh -1 c arrays pointers character

#include <stdio.h>

main() 
{
    char* str;
    char* strrev;
    int   i = 0;
    int   j = 0;
    int   c;

    printf("Enter the string\n");
    scanf("%[^\n]%*c", str);

    while (*(str + i) != '\n')
    {
        i++;
    }

    for (c = i; c >= 0; c--)
    {
        *(strrev + j) = *(str + c);
        j++;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的反转字符串的代码.当我编译代码时,它会出错segmentation fault.有人帮助我理解错误并实现我的错误.谢谢

unw*_*ind 5

有很多问题:

  • 你永远不会为str或分配内存strrev.这就是崩溃的原因; 写入未初始化的指针会调用未定义的行为,通常会导致seg错误.
  • scanf()当您可以使用时,您正在使用复杂的转换fgets().
  • 您应该使用strlen()而不是循环来查找字符串的结尾.