0

I am using scanf_s to two different inputs and place them into char arrays. I have attached the code and the output it gives

char firstName[30];
char lastName[30];


int main() {

// Input Name
printf("Please input your name: ");
scanf_s("%s %s", firstName, 30, lastName, 30);

printf("%s %s", firstName[30], lastName[30]);
_getch();

return 0;
}

the output is:

Please input your name: Jane Smith
(null) (null)

any help to this problem would be great because any scanf_s that I do won't work and its driving me crazy.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Your call to printf() is bad: Instead of the buffers themselves, you are passing it the values of characters beyond the buffer, which could be anything. You're (un)lucky they happen to be zero. – Medinoc May 09 '17 at 08:55
  • Detail: `30` is an `int`. To comply with Std C, Lib K., the size argument should be `size_t` --> `scanf_s("%s %s", sizeof firstName, sizeof firstName, lastName, sizeof lastName);` Code has other problems too. – chux - Reinstate Monica May 09 '17 at 13:31
  • Consider accepting an answer if your problem is solved. – Marievi May 18 '17 at 13:06

1 Answers1

4

Your scanf_s call is fine. What you need to change is line :

printf("%s %s", firstName[30], lastName[30]);

Using printf like this, you are trying to print the element in position 30 of firstName and lastName arrays, which not only asks to print a specific position instead of the whole array, but also is out of your arrays' bounds. This invokes undefined behaviour.

Replace it with :

printf("%s %s", firstName, lastName);
Marievi
  • 4,951
  • 1
  • 16
  • 33