3

I am taking an Intro to C class and I am wondering: why is an ampersand (&) not needed when assigning a string to a character array in C?

For instance, I learned char name[10]; scanf("%s", name);assigns a string to a character array. However, we've learned that input assignment to a variable looks like scanf("%d", &intVariable); for example.

Why is the scanf statement not scanf("%s", &name); ?

mperic
  • 118
  • 9

1 Answers1

3

The conversion specification %s in scanf expects an argument of type char *. Variable name is of type char [] (an array of char).
In C, array names converted to pointer to its first element when passed as an argument to a function. So name already is converted to char * type when passed to scanf and you do not need to put & before it. Placing & before name will give the address of the array itself, i.e its type will be pointer to an array of char (char (*)[]). Pointer to char and pointer to an array of char both are different type and hence incompatible.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • A comment would be appreciated giving the reason for the downvote? – haccks Sep 22 '19 at 20:55
  • While this is entirely correct it does not explain why giving the address of the array is wrong. Among other things, it's the same address, right? And in C++ we probably *would* define a template function that takes the address (or a reference) to an *array*, right? In order to avoid these pesky out-of-bound writes, right? – Peter - Reinstate Monica Sep 22 '19 at 21:00
  • It does answer why. *it's the same address, right?*: yes, but that doesn't mean they have the same type. *And in C++ we probably would define a template function that takes the address (or a reference) to an array, right?*: **C is not C++**. *In order to avoid these pesky out-of-bound writes, right?*: This one is out-of-bound for this question. – haccks Sep 22 '19 at 21:08
  • Well, you don't explain *why* one pointer is better than the other, right? Hint: Your answer does not contain "because". And of course C is not C++ but even in C the [] operator knows and needs the size of its operand, so why does C not take a whole array address in scanf? (Hint: Because it is not part of the core language but a library function and most likely was originally not an intrinsic and because the language's type system was not designed to handle that, hence the C++ comparison) etc. Simply stating "will give the address of the array itself" does not explain why that would be wrong. – Peter - Reinstate Monica Sep 23 '19 at 04:00