I recently embarrassed myself while explaining to a colleague why
char a[100];
scanf(\"%s\", &a); // notice a & in front of \'a\'
is ve
Well, the &a
case should be obvious. You take the address of the array, exactly as expected.
a
is a bit more subtle, but the answer is that a
is the array. And as any C programmer knows, arrays have a tendency to degenerate into a pointer at the slightest provocation, for example when passing it as a function parameter.
So scanf("%s", a)
expects a pointer, not an array, so the array degenerates into a pointer to the first element of the array.
Of course scanf("%s", &a)
works too, because that's explicitly the address of the array.
Edit: Oops, looks like I totally failed to consider what argument types scanf actually expects. Both cases yield a pointer to the same address, but of different types. (pointer to char, versus pointer to array of chars).
And I'll gladly admit I don't know enough about the semantics for ellipsis (...), which I've always avoided like the plague, so looks like the conversion to whichever type scanf ends up using may be undefined behavior. Read the comments, and litb's answer. You can usually trust him to get this stuff right. ;)