【问题标题】:C Program isn't printing strings properlyC 程序没有正确打印字符串
【发布时间】:2020-07-04 11:44:35
【问题描述】:

这是我目前的代码:

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

#define WORD_LEN 20

int main(int argc, char *argv[]) {

    int i;
    char smallest_word[WORD_LEN + 1],
         largest_word[WORD_LEN + 1],
         current_word[WORD_LEN + 1];

    current_word == argv[1];
    strcpy(smallest_word, (strcpy(largest_word, current_word)));

    for (i=2; i<argc; i++) {
        current_word == argv[i];

        if (strcmp(current_word, smallest_word) < 0) {
            strcpy(smallest_word, current_word);
        }
        else if (strcmp(current_word, largest_word) > 0) {
            strcpy(largest_word, current_word);
        }
    }

    printf("\nSmallest word: %s", smallest_word);
    printf("\nLargest word: %s", largest_word);

    return 0;
}

这个程序的重点是从命令行获取参数(单词)并比较它们以查看哪个是最小的和最大的(AKA 字母顺序)。我觉得我的程序已经关闭并且它应该可以工作,但是当我尝试运行代码时,输​​出是奇怪的波浪状字符。如果我的输入如下,那么输出将是:

输入:

./whatever.exe hello there general kenobi

输出:

Smallest word: ▒
Largest word: ▒

而正确的输入输出应该如下:

输入:

./whatever.exe hello there general kenobi

输出:

Smallest word: general
Largest word: there

我不确定这是类型问题,还是我的程序完全有问题。我期待任何和所有的反馈

【问题讨论】:

  • current_word == argv[1]; 什么都不做 - 比较被丢弃的指针。我怀疑你想让strcpy(current_word, argv[1]); 复制"hello"。节省时间,启用所有编译器警告。
  • @chux-ReinstateMonica 就是这样!非常感谢!
  • C11 Standard - 6.3.2.1 Other Operands - Lvalues, arrays, and function designators(p3) "...类型为 "array of type" 的表达式被转换为类型为 "pointer to type"的表达式> 指向数组对象的初始元素并且不是左值。"

标签: c string pointers char command-line-arguments


【解决方案1】:

分配字符串的方法错误

下面比较2个指针,然后丢弃结果。 2个地方

current_word == argv[1];  // Not the needed code
current_word == argv[i];

需要字符串的副本。

strcpy(current_word, argv[1]);

这样的代码是不稳定的,因为argv[1] 的字符串长度可能会满足/超过数组current_word 的大小。更好的代码会测试。示例:

if (strlen(argv[1]) >= sizeof current_word)) {
  fprintf(stderr, "Too big <%s>\n", argv[1]);
  exit(EXIT_FAILURE);
}
strcpy(current_word, argv[1]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多