0
    /* Variables */
    int num;
    char array[5]; // Array must also include NULL char
    char new;

    /* Accepting user input */
    printf("Please enter 5 characters below:\n");
    scanf("%c\r", &array[0]);
    scanf("%c\r", &array[1]);
    scanf("%c\r", &array[2]);
    scanf("%c\r", &array[3]);
    scanf("%c", &array[4]);
    /* Displaying input as string */
    printf("%s", array); 

I am trying to create a basic program that creates a string that accepts chars one after the other. I know that arrays start at 0 and end with the null character so I made my array[5] so if I inputted "a" "b" "c" "d" "e" I would get the output string "abcde" plus the null character. Sometimes it works with one set of characters but not another. If I input "q" "w" "e" "r" "t" i might get the output "qwerta". How do I stop it from displaying that last character?

I understand that the reason why this character being displayed is that it is undefined and will show whatever value is at that memory location but I don't know how to fix it.

I have tried to include different escape sequences, putting spaces in the scanf and printf statements but what am I doing wrong?

  • Where did you set the last character as `'\0'`? – Chris Dec 13 '22 at 22:14
  • 1
    char arrays only end with a null char if you leave enough space for one and put one in. It is not automatic, but is required to use it as a C style "string". `char array[5];` => `char array[6];`. `scanf("%c", &array[4]);` => `scanf("%c", &array[4]); array[5] = '\0';` – Avi Berger Dec 13 '22 at 22:15
  • Oh right thank you that explains it, yeah i had it in my head that it was automatic – LeonidasEng Dec 13 '22 at 22:20
  • 2
    If you want to print the array content without needing a null character, you can change the line `printf("%s", array); ` to `printf("%.5s", array); `. That way, `printf` will not attempt to print more than 5 characters, so it won't attempt to read out of bounds of the array. – Andreas Wenzel Dec 13 '22 at 22:22
  • C is a very simple language, almost nothing is automatic. – Barmar Dec 13 '22 at 22:23
  • `printf("%s", array);` fails as `"%s"` expects a matching _string_. `array[]` is not a string as it lacks a _null character_. To print the character array `printf("%.*s\n", 5, array);` That will print the first 5 characters or up to a null character, which ever is first. – chux - Reinstate Monica Dec 13 '22 at 22:24

1 Answers1

1

You have a character array with size 5. You read a character into each of the five elements of the array. This does not leave space for the null character, and you do not explicitly set the last char equal to '\0'. Thus this is not a null terminated string, and printing it as a string with the %s specifier in printf has undefined behavior.

Chris
  • 26,361
  • 5
  • 21
  • 42