Scanf неохотно стирает массив символов - PullRequest
3 голосов
/ 22 июля 2011

См. Следующую программу:

#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 ]

4 голосов
/ 22 июля 2011

Измените строку сканирования на эту:

scanf("%hd",&n);

Смотрите здесь: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

4 голосов
/ 22 июля 2011

Попробуйте сделать "n" вместо "int" вместо int, запустите его и посмотрите, исправит ли это.Если так, я объясню почему.

Как указывает Сорен, scanf ожидает чтения 32-битных данных;когда ширина буфера составляет всего 16 бит, дополнительная память перетасовывается туда, где она не принадлежит, по существу, обнуляя память (при условии, что пользователь вводит достаточно малое число).

...