w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
printf printing more than one element of an array

You are not asking for userIn[2]. You are asking for a string that begins at &userIn[2]. Format specifier %s means "string". The string that begins at &userIn[2] is indeed "er". Which is what you see as your output.

If you want to print a single character, you can use %c format specifier and pass in userIn[2] instead of &userIn[2]

printf("%c
", userIn[2]);

Alternatively, you can use %s, but in this case you have to explicitly limit the length of the string to be printed through precision specifier, as in

printf("%.1s
", &userIn[2]);

The above means: print the string, but don't output more than 1 character.

P.S. As it has been noted in the comments, your scanf call is incorrect. It should be either scanf("%s", userIn) or scanf("%s", &userIn[0]), but not what you have now. What you have now will typically "work", but the type of the pointer is still incorrect. Many compilers will issue a warning about this.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.