【问题标题】:Passing strings results in empty strings in C?传递字符串会导致C中的空字符串?
【发布时间】:2014-04-30 18:00:33
【问题描述】:

我从 main() 中的用户那里得到了一些字符串,我想将这些字符串作为参数传递给另一个函数。当我运行调试时,我可以看到只有最后一个参数保存输入的字符串,而前两个参数为空。当我将字符串定义为全局时,一切正常,怎么会?

我还尝试在从用户那里获取字符串后立即打印它们并且它们存储正常。

下面是部分代码:

  char temp_destination[20];
    char temp_old_date[6];
    char temp_new_date[6];

    printf("Please enter destination, flight date and new date to update\n");
    printf("Destenation: ");
    scanf("%s",temp_destination);
    printf("Current date: ");
    scanf("%s",temp_old_date);
    printf("New Date: ");
    scanf("%s",temp_new_date);
    update_flight_date(database,temp_destination,temp_old_date,temp_new_date);

【问题讨论】:

  • 确保scanf 不会溢出您的数组。在scanf 中指定最大宽度(例如scanf("%19s", temp_destination);),或者更好的是:改用fgets
  • 代码,如图所示,没有问题。请尝试创建一个有问题的SSCCE,并显示出来。
  • 如何输入日期?
  • @n.m. - 例如010100
  • 请记住,C 中的字符串总是有一个额外的终止符。

标签: c string function arguments


【解决方案1】:
    char temp_destination[20];
    char temp_old_date[6];
    char temp_new_date[6];

当用户输入超过这些长度时,内存将被彼此覆盖。在这种情况下,因为它们在堆栈(本地)上,所以它们会覆盖它们自身(未定义的行为)。在全局变量中,它也发生了,但它只是你的程序正在运行。

所以你真的应该确保用户输入不应该超过你定义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2012-11-04
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多