3

See the following program:

#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;
}

It is peculiar how that specific scanf erases the s3 array without even being implied. How come this happens?

Perception
  • 79,279
  • 19
  • 185
  • 195
andreihondrari
  • 5,743
  • 5
  • 30
  • 59
  • 1
    Please be more precise with terminology. Arrays don't "become null"; null is a state for pointers, and the memory for the array is still there. What has happened is that the buffer now appears to contain an empty string, i.e. its first character has been set to '\0'. (The ASCII NUL or "null byte", `'\0'`, should not be confused with the `NULL` pointer value.) – Karl Knechtel Jul 22 '11 at 20:46

2 Answers2

4

Try making "n" an "int" rather than a "short int", run it, and see if that fixes it. If so, I'll explain why.

As Soren points out, scanf expects to read in 32 bits of data; when the buffer is only 16 bits wide, the extra memory is shuffled somewhere it doesn't belong, essentially zeroing out memory (assuming the user enters a small enough number).

Patrick87
  • 27,682
  • 3
  • 38
  • 73
  • 1
    %d expects a pointer to an integer, you give it a pointer to something shorter than that and hence corrupts the stack. If you really want to read something into a `short`, then read the scanf man page for the correct %% string – Soren Jul 22 '11 at 19:46
  • 1
    Aww, Soren... I would have told him. I just wasn't sure that was all that was wrong with it. – Patrick87 Jul 22 '11 at 19:47
  • @Soren: Huh... Didn't notice that... Nice! – zw324 Jul 22 '11 at 19:47
  • 2
    Oh, forgot to adapt the format specifier to SHORT INT.. should have tryed %hd in that scanf (works also). Thanks for feedback anyway. – andreihondrari Jul 22 '11 at 19:51
  • @Thomas Carpenter: what if the user enters a bigger number? Would that entry modify the string into something... else? – andreihondrari Jul 24 '11 at 13:37
4

Change your scan line to this:

scanf("%hd",&n);

See here: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

faraday
  • 324
  • 2
  • 7
  • 14