1

I had encountered a contradiction - in my point of view - when using arrays as arguments in scanf() function with characters and with integers. in Deitel and Deitel book, I was studying character handling library and it introduced that when - for instance - assigning: "char word[ 20 ]" and then "scanf( "%s", word );", here the scanf() function doesn't need the & operator. But when assigning: "int array[ 10 ]" and then when scanning the input from the user, here it needs the & operator!! Could anybody explain this for me please ?

Priya
  • 334
  • 3
  • 8
  • 1
    Please give an example to your `scanf` with integer arrays. Usally it's `scanf("%d", &array[i])` or `scanf("%d", array+i)`....... in a char array the `%s` scans into a string, not a char, therefore it uses the entire array.... – Roy Avidan Jul 09 '18 at 11:28
  • Possible duplicate of [Why doesn't scanf need an ampersand for strings and also works fine in printf (in C)?](https://stackoverflow.com/questions/1931850/why-doesnt-scanf-need-an-ampersand-for-strings-and-also-works-fine-in-printf-i) – anoopknr Jul 09 '18 at 11:34

2 Answers2

1
char word[20];
scanf("%s", word);

It will read the whole string (collection of characters) the user typed into word. So if I type "Hi", then word[0] would be 'H' and word[1] would be 'i'.

int array[10];
scanf("%d", &array[0]); // Stores the number the user typed into 'array[0]'
scanf("%d", &array[1]); // Stores the number the user typed into 'array[1]'

Here we use the &, but also we access an element of the array, since the format specifier %d is for a number.

In order to get the analogy, consider this example:

char word[20];
scanf("%c", &word[0]);
scanf("%c", &word[1]);

Here the format specifier, is asking for a character (and not a collection of characters (i.e. a string)).

gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

Two things to remember:

First of all, unless it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array. So when you pass an array expression to a function like scanf, what the function actually receives is a pointer to the first element.

Secondly, the %s conversion specifier will read a sequence of characters until it sees a whitespace character or hits end-of-file, and it stores that sequence to the array starting at the passed address. By contrast, the %c conversion specifier only reads a single character from the input stream and stores it to the passed address.

John Bode
  • 119,563
  • 19
  • 122
  • 198