Up until now I have always accessed a pointer to a struct array thus:
struct blah *ptr; ptr[10].member = 1;
I recently became aware of another way:
struct blah (*array_ptr)[]; (*array_ptr)[10].member = 1;
The only restriction I've found, is it prohibits array->member
access forcing [] usage.
Question: Are there any pros/cons to the explicit [] method to either a) humans or b) compilers between either method?
For humans, I guess it makes it explicit that the pointer is to an array, as opposed to the 'normal' use where it is ambiguous.
CodePudding user response:
Up until now I have always accessed a pointer to a struct array thus:
struct blah *ptr; ptr[10].member = 1;
That demonstrates a pointer to a struct (that happens to be an element of an array of at least 11 such structs), not a pointer to an array of structs. It is, however, the pointer type to which an array of struct blah
would decay.
I recently became aware of another way:
struct blah (*array_ptr)[]; (*array_ptr)[10].member = 1;
That is a pointer to an array of [an unspecified number of] structs.
The addresses to which these two pointers point may be the same, but the pointers have different types.
The only restriction I've found, is it prohibits
array->member
access forcing [] usage.
You can use either form to access struct blah
objects indirectly. Yes, the syntax for doing so is different between the two cases, on account of the pointer types being different.
Question: Are there any pros/cons to the explicit [] method to either a) humans or b) compilers between either method?
I daresay most people find the structure pointer variation easier to read and understand than the array pointer version. It ought to make no difference at all to a compiler, because if array_ptr
points to the array whose first element is *ptr
, and that array indeed does have at least 11 elements, then the two example assignments are 100% equivalent.
For humans, I guess it makes it explicit that the pointer is to an array, as opposed to the 'normal' use where it is ambiguous.
A pointer can always be considered to point to an array, though that may be an array of length 1. There is no particular usefulness in trying to draw a distinction, at least not by varying the type of the pointer. It gets more interesting and more useful when you have pointers to arrays with known length (example: struct blah (*array11_ptr)[11];
), but I don't see many use cases for your unspecified-length version.