+ 17

When using scanf with a char array in C why do both forms work whether you use & (address of) or not for the array name? E.g.

#include <stdio.h> int main() { char text[10]; char text1[10]; scanf("%s", text); printf("%s", text); scanf("%s", &text1); printf("%s", text1); }

25th Sep 2018, 8:23 AM
Sonic
Sonic - avatar
6 ответов
+ 16
Actually KrOW you're right!! I verified this using my code: https://code.sololearn.com/cVbuSnY7BOOM/?ref=app
26th Sep 2018, 8:42 AM
Sonic
Sonic - avatar
+ 14
KrOW What if I had said char **arrptr=&text1 ? In this case &text1 which is arrptr would not be text1 would it? So how can we say that the address of an array is the same as the address of its first element?
26th Sep 2018, 8:04 AM
Sonic
Sonic - avatar
+ 3
Because array would be seen like constant pointers that point to itself then text is the value of this pointer (adress of itself) &text is the adress of itself then text and &text have same value
25th Sep 2018, 9:14 AM
KrOW
KrOW - avatar
+ 3
Yes... Adress of an array is same as adress of first element ;)
26th Sep 2018, 11:29 AM
KrOW
KrOW - avatar
+ 3
KrOW basically answered the question XD. The name of a one-dimensional array is a constant pointer. Although you are right with text being equal to the address stored in the pointer. &text is the address in memory of the array pointer, and the compiler should have an error or atleast have a warning shown
27th Sep 2018, 5:53 PM
Caleb Cook
Caleb Cook - avatar
+ 2
When you pass a variable into a function, the function creates a copy of that variable and anything that the function does is applied ONLY to the copy. But when you pass an array to a function, it's different; the address to the array is always passed and no copy is created. Anything the function does to the array is done to the original. So if you have a very large array, all of that copying that would otherwise have to be done is eliminated.
27th Sep 2018, 6:49 PM
Robert Warner