-3

I have some problem for this output. Also, I also want some examples on how to use char *str.

int main() {
    char str[5];
    scanf_s("%c", &str);
    printf("%s", str);
    return 0;
}

The output came out weird for the input "VI".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Khor
  • 15
  • 7

2 Answers2

2

scanf_s takes pointer as its argument. So you don't need to use &str, because str is implicitly converted to a pointer when used in expressions like an argument expression. You can also pass the buffer size as a parameter in scanf_s.

So you can use

scanf_s("%c", str, 5);

where 5 is the buffer size. Passing a specific buffer size will restrict you taking input more than the size which is missing scanf. In scanf you may take more input than the array or string size (like declared string is char str[4], but you may take input 'Hello') which later causes crashing the program due to overflow. But using particular buffer size in scanf_f will not allow you taking more input than the buffer size. This is where the scanf_s comes in.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shakibuz_Zaman
  • 260
  • 1
  • 14
0

Firstly, you need a pointer as an argument to scanf_s, which is exactly what str decays to when passed to a function, so you don't need the & operator, and also you need to specify a buffer size:

scanf_s("%c", str, 5);

You can find the Microsoft documentation here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • See also *[How come an array's address is equal to its value in C?](https://stackoverflow.com/questions/2528318)*, *[What does getting the address of an array variable mean?](https://stackoverflow.com/questions/38202077)*, and *[Address of an array](https://stackoverflow.com/questions/8412694)*. – Peter Mortensen Aug 01 '19 at 21:09