Reputation: 1
Is it good coding practice, to use sizeof(struct) when the struct has a fixed length array?
#define NUM_TRACKS 10
#define NUM_SAMPLES 250
typedef struct _DATA_PROC
{
uint16_t count[NUM_TRACKS] ;
int16_t data[NUM_TRACKS][NUM_SAMPLES];
} tDataProcessing ;
tDataProcessing* tDp = malloc(sizeof(tDataProcessing)) ;
Upvotes: 0
Views: 260
Reputation: 310980
For starters in expressions, with rare exceptions including the sizeof
operator, arrays are implicitly converted to pointers to their element types.
So for example the array
int16_t data[NUM_TRACKS][NUM_SAMPLES];
is converted in expressions like
int16_t ( *data )[NUM_SAMPLES];
not as you wrote in a comment like
int16_t** data
However a declaration is not an expression. So the sizeof
operator returns the number of bytes to accommodate all data members of the structure without any implicit conversion.
From the C Standard (6.5.3.4 The sizeof and alignof operators)
2 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
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
enum { N = 10 };
int a[N];
printf( "sizeof( a ) = %zu\n", sizeof( a ) );
struct A
{
int a[N];
};
printf( "sizeof( struct A ) = %zu\n", sizeof( struct A ) );
return 0;
}
Its output is
sizeof( a ) = 40
sizeof( struct A ) = 40
Upvotes: 0
Reputation: 13171
I personally prefer to use the pointer variable itself rather than the type:
tDataProcessing *tDp = malloc(sizeof *tDp);
This is sometimes clearer in cases with pointers buried in types and such.
Upvotes: 1