Lachlan Dawson
Lachlan Dawson

Reputation: 1

scanf_s returning Null every time

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.

Upvotes: 0

Views: 81

Answers (1)

Marievi
Marievi

Reputation: 5011

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);

Upvotes: 4

Related Questions