Question

how to get the element count of an array that is part of a struct without defines or const fields?

I have a struct that contains an array.

How can I compute the array element count with standard C, when I do not want to resort to defines or const fields?

typedef struct TEXTUREBUCKET {
    long tpage;
    long nVtx;
    D3DTLBUMPVERTEX vtx[2048];
} TEXTUREBUCKET;

static inline size_t TextureBucketVertexCount() {
    return (sizeof(TEXTUREBUCKET) - offsetof(TEXTUREBUCKET, vtx)) / sizeof(D3DTLBUMPVERTEX); // works as long as vtx is the last member
}

 4  46  4
1 Jan 1970

Solution

 5

You can accomplish this with the following expression:

sizeof(((TEXTUREBUCKET*)0)->vtx) / sizeof(((TEXTUREBUCKET*)0)->vtx[0]

Note that there is no NULL pointer dereference here because the sizeof operator does not actually evaluate its operand (unless it's a variable length array). The expression is only parsed to determine its type.

This is spelled out in section 6.5.3.4p2 of the C standard regarding the sizeof operator:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

2024-07-16
dbush