【问题标题】:Scanf erases a char array unwillinglyScanf 不情愿地擦除了一个 char 数组
【发布时间】:2011-10-11 07:55:34
【问题描述】:

查看以下程序:

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

main(void){
  printf("Array concatenateor\n-------------------------\n");

  //declarations
  char s1[50],s2[50],s3[50];
  short int n=0;

  //Array initialisation
  printf("Array 1: ");
  gets(s1);
  printf("Array 2: ");
  gets(s2);

  strcpy(s3, s1); //asure initial form of s1 in s3
  strcat(s1, s2); //concatenate s1 with s2  
  //at this point s1 is in the concatenation form and s3 is s1's initial form

  printf("Arrays concatenated with STRCPY: \"%s\"\n", s1); //print concatenation, s3 ok
  printf("Number of characters to concatenate: "); //scan number, s3 ok
  scanf("%d",&n); //beyond this point s3 becomes null... peculiar
  printf("S3: %s\n",s3);    //this is the proof of s3 being null
  strncat(s3,s2,n); //s3 concatenates with n chars of s2
  printf("Arrays concatenated with STRNCAT(%d chars): %s\n", n, s3);  //print s3
  system("PAUSE");
  return 0;
}

奇怪的是,特定的 scanf 如何在没有暗示的情况下擦除 s3 数组。这是怎么回事?

【问题讨论】:

  • 请用更准确的术语。数组不会“变为空”; null 是指针的状态,数组的内存仍然存在。发生的事情是缓冲区现在似乎包含一个空字符串,即它的第一个字符已设置为 '\0'。 (ASCII NUL 或“空字节”'\0' 不应与 NULL 指针值混淆。)

标签: c string scanf erase strcat


【解决方案1】:

把你的扫描线改成这样:

scanf("%hd",&n);

请看这里:http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

【讨论】:

    【解决方案2】:

    尝试将“n”设为“int”而不是“short int”,运行它,看看是否能解决问题。如果是这样,我会解释原因。

    正如 Soren 所指出的,scanf 期望读取 32 位数据;当缓冲区只有 16 位宽时,额外的内存会被打乱到它不属于的地方,基本上将内存归零(假设用户输入的数字足够小)。

    【讨论】:

    • %d 需要一个指向整数的指针,你给它一个指向比它更短的指针,因此会破坏堆栈。如果您真的想将某些内容读入short,请阅读 scanf 手册页以获取正确的 %% 字符串
    • 哇,索伦……我会告诉他的。我只是不确定这一切都是错的。
    • @Soren:嗯...没注意到...不错!
    • 哦,忘记将格式说明符调整为 SHORT INT.. 应该在那个 scanf 中尝试 %hd (也可以)。无论如何感谢您的反馈。
    • @Thomas Carpenter:如果用户输入一个更大的数字怎么办?该条目会将字符串修改为其他内容吗?
    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2015-11-22
    • 2015-08-24
    • 2011-08-26
    相关资源
    最近更新 更多