Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays as scanf's function arguments. Adress operator

#include <stdio.h>

int main(void)
{
  char s[32];

example_1:
  scanf("%s", s);
  printf("%s\n", s);

example_2:
  scanf("%s", &s[0]);
  printf("%s\n", s);

example_3:
  scanf("%s", &s);
  printf("%s\n", s);
}
  1. Why does #3 work the same way as other 2?

  2. Is #3 valid at all? Why?

like image 488
HighPredator Avatar asked Jan 29 '26 03:01

HighPredator


1 Answers

  1. Variant one depends on array decay, and is thus valid.

    (Arrays decay to pointers to their first element in most contexts, exceptions are: Address-of (&s), sizeof s, _Alignas(s) and _Alignof(s).)

  2. Variant two does what array-decay would do manually and more verbose, and is thus worse.

  3. Variant three is strictly Undefined Behavior, though it happens to work on most implementations.
    The sticking point is that &s is not of type char* after default promotions, though it points to the right address.

Seems to work is the most treacherous subset of UB.

like image 52
Deduplicator Avatar answered Jan 30 '26 20:01

Deduplicator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!