Van Tr
Van Tr

Reputation: 6101

What does struct_type[1] mean?

I found some code that gets the size of struct like this:

sizeof(struct struct_type[1]);

I tested and it does return the size of struct_type.

And

sizeof(struct struct_type[2]);

returns twice the struct size.

Edit:

struct_type is a struct, not an array:

struct struct_type {
    int a;
    int b;
};

What does struct_type[1] actually mean?

Upvotes: 27

Views: 1489

Answers (3)

haccks
haccks

Reputation: 106012

For the declaration

int arr[10];

size of array can be calculated by either using arr as an operand or int [10]. Since sizeof operator yields the size based on the type of operand, both sizeof(arr) and sizeof (int [10]) will return the size of array arr (ultimately arr is of type int [10]).

C11-§6.5.3.3/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 is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

Similarly, for an array of struct struct_type

struct struct_type a[1];

size can be calculated either by sizeof (a) or sizeof(struct struct_type[1]).

Upvotes: 7

sps
sps

Reputation: 2720

Just like:

sizeof(int[1]); // will return the size of 1 int

and

sizeof(int[2]); // will return the size of 2 ints

So does:

sizeof(struct struct_type[1]); // return size of 1 `struct struct_type'

and

sizeof(struct struct_type[2]); // return size of 2 `struct struct_type'

Here struct struct_type[1], and struct struct_type[2] simply represent arrays of elements of type struct struct_type, and sizeof of is just returning the size of those represented arrays.

Upvotes: 13

Sergio
Sergio

Reputation: 8209

Remember sizeof syntax:

sizeof ( typename );

Here typename is struct struct_type[N] or in more readable form struct struct_type [N] which is an array of N objects of type struct struct_type. As you know array size is the size of one element multiplied by the total number of elements.

Upvotes: 24

Related Questions