Why does such a struct contain two array fields containing only one element?

前端 未结 2 1728
青春惊慌失措
青春惊慌失措 2021-01-11 19:17

Please Note: This question is not a duplicate of ( One element array in struct )

The following code is excerpted from the Linux kernel source (versi

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-11 20:18

    My best guess: The addresses of these fields are used much more often than their actual values. In this case, making them size-1 arrays saves typing & every time their address is needed, since in C using the name of an array in an expression is in nearly all cases exactly equivalent to taking the address of its first element:

    int x;
    int y[1];
    
    function_that_needs_address_of_int(&x);
    function_that_needs_address_of_int(y);
    function_that_needs_address_of_int(&y[0]);    // Identical to previous line
    

    (As others have pointed out in the comments, it can't be that the fields are being used as a hack for variable-length arrays, since there is more than one and they don't appear at the end of the struct.)

    [EDIT: As pointed out by user3477950, an array name is not always identical to the address of its first element -- in certain contexts, like the argument to sizeof, they mean different things. (That's the only context I can think of for C; in C++, passing an array name as an argument can also enable a template parameter's type to be inferred to be a reference type.)]

提交回复
热议问题