Scanf不情愿地擦除了一个char数组

时间:2011-07-22 19:36:33

标签: c string scanf erase strcat

请参阅以下程序:

#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阵列是特殊的。怎么会发生这种情况?

2 个答案:

答案 0 :(得分:4)

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

正如Soren指出的那样,scanf希望读取32位数据;当缓冲区只有16位宽时,额外的内存在它不属于的某个地方被洗牌,基本上将内存清零(假设用户输入的数字足够小)。

答案 1 :(得分:4)

将扫描线更改为:

scanf("%hd",&n);

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