C: why not & for lines in scanf () function?

Possible duplicate:
Why doesn't scanf need an ampersand for strings and also works fine in printf (in C)?

In C, when we use the scanf() function to enter the user, we always use the & sign in front of the variable. For instance:

  scanf("%d", &number); scanf("%c", &letter); 

This ensures that our input is stored in the appropriate address. But in the case of a string, we do not use & .

Why is this?

+4
source share
2 answers

A "string" in C is the address of the character buffer.
You want scanf fill memory in the buffer pointed to by the variable.

In contrast, int is a block of memory, not an address. To scanf fill this memory, you need to pass its address.

+12
source

Since the identifier buf in char buf[512]; degrades to a pointer to the first element of the array, you do not need to point to a pointer to a buffer in the scanf argument. By passing &buf pointer passed by scanf is now a bi-directional pointer (this is a pointer to a pointer to the beginning of the buffer) and is likely to cause a program crash or other bad behavior.

+1
source

Source: https://habr.com/ru/post/1391772/


All Articles