Joseph Piché
Joseph Piché

Reputation: 586

Result of 'sizeof' on array of structs in C?

In C, I have an array of structs defined like:

struct D
{
    char *a;
    char *b;
    char *c;
};

static struct D a[] = {
    {
        "1a",
        "1b",
        "1c"
    },
    {
        "2a",
        "2b",
        "2c"
    }
};

I would like to determine the number of elements in the array, but sizeof(a) returns an incorrect result: 48, not 2. Am I doing something wrong, or is sizeof simply unreliable here? If it matters I'm compiling with GCC 4.4.

Upvotes: 40

Views: 106667

Answers (4)

lordvoldemort
lordvoldemort

Reputation: 85

ssize_t portfoySayisi = sizeof(*portfoyler);

THIS ONE WORKS

Upvotes: -3

Alok Singhal
Alok Singhal

Reputation: 96251

sizeof a / sizeof a[0];

This is a compile-time constant, so you can use it to, for example, create another array:

#define N sizeof a / sizeof a[0]
int n_a[N];

Upvotes: 50

ittays
ittays

Reputation: 121

sizeof returns the size in memory of the passed element. By dividing the size of an array by a single element size, you get the elements count.

Note that the element size may include some padding bytes as well. For this reason, a padded struct (e.g. when a char member is followed by a pointer) will have a sizeof value greater than it members size sum.

On the other hand, don't let it bother you when counting elements in an array: sizeof(a) / sizeof(a[0]) will still work as smooth as expected.

Upvotes: 12

Grandpa
Grandpa

Reputation: 3253

sizeof gives you the size in bytes, not the number of elements. As Alok says, to get the number of elements, divide the size in bytes of the array by the size in bytes of one element. The correct C idiom is:

sizeof a / sizeof a[0]

Upvotes: 50

Related Questions