0

I have begun learning C on my own. I am using Head First C.

The below program is a bit confusing to me:

#include <stdio.h>
int main()
{
    puts("Hello World!");
    puts("Enter your favorite Number:");
    char arrayOfNumbers[3];
    scanf("%2s",arrayOfNumbers);
    //printf(arrayOfNumbers);
    char s[] = {'a','b','c','d','e'};
    printf(s);
    return 0;
}

The output of this program is :

Hello World!

Enter your favorite Number:

1

abcde1

What I don't get is, inspite of the fact that I am copying the input '1' in the array arrayOfNumbers, and then I am printing the array 's', the output contains the 1 I entered. How is the input being copied to the array 's'?

Sid
  • 4,893
  • 14
  • 55
  • 110

2 Answers2

1

The char s[] is missing the terminating null byte '\0' and read past the end of the array by printf. So it prints the next value on the stack I suppose. Fix it like this and see

#include <stdio.h>
int main()
{
    puts("Hello World!");
    puts("Enter your favorite Number:");
    char arrayOfNumbers[3];
    scanf("%2s",arrayOfNumbers);
    //printf(arrayOfNumbers);
    char s[] = {'a','b','c','d','e','\0'}; // see the added '\0' byte
    printf(s);
    return 0;
}

the strings in C require an unprintable byte to mark the end of the string, there are many functions that expect this like strlen for instance, printf is one of them. If you are on Linux, valgrind would have told you about it

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

Check the code below: You should have a NULL terminated string in order for the printf to print the string. Printing a string without format specifier can be dangerous. If your string has some format specifer like %d or %s then the printf() will be expecting that there will be an argument after this and it might read some value from your stack. So IMO you should use format specifier %s in order to print strings

#include <stdio.h>
int main()
{
    puts("Hello World!");
    puts("Enter your favorite Number:");
    char arrayOfNumbers[3];
    scanf("%2s",arrayOfNumbers); 
    printf("%s\n",arrayOfNumbers); /* or printf(arrayOfNumbers); */
    char s[] = {'a','b','c','d','e','\0'};
    printf("%s",s); /* or printf(s); */
    return 0;
}
Gopi
  • 19,784
  • 4
  • 24
  • 36