Semantics of char a[]

后端 未结 6 614
忘掉有多难
忘掉有多难 2021-02-01 23:34

I recently embarrassed myself while explaining to a colleague why

char a[100];
scanf(\"%s\", &a); // notice a & in front of \'a\'

is ve

6条回答
  •  温柔的废话
    2021-02-02 00:28

    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. ;)

提交回复
热议问题