c - 用 C 反转字符串中的字序(代码错误)

标签 c

有人可以引导我朝正确的方向前进吗?

这是一项学校作业,我似乎找不到其中的错误。 对于输入

"a b c d e f" 

我明白

"f e d c b a" and that is right.

但是对于

"1234567890 abcdefghij" i get 

"�' abcdefghij 1234567890"

有人可以引导我走向正确的方向吗?指针都错了吗?

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

int main()
{  
  char *words [100];
  char *word[11];
  char *str;
  int res, i;
  i = 0;
  res = scanf("%10s",word);
  if (res != 1) return 0;

  while ( res != EOF) {
    str = malloc(strlen(word)+1);
    strcpy(str,word);
    words[i] = str;
    res = scanf("%10s",word);
    i = i+1;
  }

  while (i>=0) {
    printf("%s ",words[i]);
    i--;
  }

  return 0;
}

最佳答案

i 从数组末尾的 1 个元素开始。奇怪的是第一个例子似乎有效。第二个没有,这并不奇怪。

尝试:

while (--i >= 0)
{
  printf("%s ", words[i]);
}

word应该是char word[11],而不是char *word[11]

关于c - 用 C 反转字符串中的字序(代码错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27911202/

相关文章:

c++ - 将变量传递给函数的成本

c - 在套接字上发送时出错错误文件描述符

c - 如何找出用户输入包含 C 中的非 ASCII 字符

C 从另一个函数输出数组

c - Makefile:没有使用变量创建目标的规则

将字符串转换为字符指针数组

c - 指向字符串的指针以及赋值和取消引用之间的区别

c - if 语句中的自增运算符

c - 如何在 C 中实现通用的、动态增长的数组?

c++ - 多线程服务器中的EnterCriticalSection和大量共享数据