C程序无法正确打印字符串

时间:2020-03-24 00:09:13

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

这是我的代码:

#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

我不确定这是否是类型问题,或者我的程序完全有问题。我期待所有反馈

1 个答案:

答案 0 :(得分:1)

分配字符串

的方式错误

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

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

而是需要 string 的副本。

strcpy(current_word, argv[1]);

此类代码code可危,因为字符串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]);
相关问题