在c中反转一个单词

use*_*830 -3 c string

这肯定很简单,但我是C的新手,我不明白为什么下面的代码是错误的.代码是字符串的简单恢复字符位置:

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

int main()
{   int i,length;
    char *word;
    scanf("%s",word);
    length = strlen(word);
    char res[length];

    for(i=0;i<length;i++){
        res[i]=word[length-1-i];
        printf("%d",res[i]);}
}
Run Code Online (Sandbox Code Playgroud)

当我输入一个字符串时,我在控制台和调试器中收到一条消息:(lldb):movb%al,(%rcx),EXC_BAD_ACCESS(code = 1,address = 0x0)

Lew*_*rin 5

char *word;
scanf("%s",word);
Run Code Online (Sandbox Code Playgroud)

写入不存在的内存位置无效.

像这样创建一个数组:char word[MAXSIZE]或者使用malloccalloc动态分配内存.而fgets不是使用scanf

一些链接让你以快乐的方式: malloc,calloc,fgets