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

Joseph Piché picture Joseph Piché · Dec 14, 2009 · Viewed 73.6k times · Source

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.

Answer

Grandpa picture Grandpa · Dec 14, 2009

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]