• Status: Solved
• Priority: Medium
• Security: Public
• Views: 342

# size of a struct?

Hi,

I need to find the size of a struct, please see below for the code. I am working on Linux. I need to find the size of user[].

Cheers,

{
char time[10];
};

0
daveyj1572
1 Solution

Commented:
struct login 20 bytes cause each char is 1 byte long
0

Commented:
also u can use sizeof to see the size of any structure

size_t s = sizeof(struct STRUCT_NAME);

printf("%d", s);
0

Commented:
if user[NUM_ELEM]
you can calculate it by sizeof(struct login) * NUM_ELEM
0

Author Commented:
the second option gives me:

'sizeof applied to incomplete type'

that's what I thought I would use but was presented with this error

0

Author Commented:
the second option gives me:

'sizeof applied to incomplete type'

that's what I thought I would use but was presented with this error

0

Commented:
Because C can have internal structure padding, you CANNOT simply add up the sizes of the internal members of the structs - that's what the sizeof operator is for:

As shown above, the correct way to get the size of the struct is:

size_t s = sizeof(struct STRUCT_NAME);

Now you CAN'T say:

You have to give C the array size when you initialize a variable.

You could do:

which creates a pointer to structures of type login, but allocates no storage.  At runtime, you could allocate 10 structures by saying

and then access them like:

strcpy(user[0].time, "09:15");

etc...

The size of memory allocated would be 10 * sizeof(login), same as in the malloc.  However the size of user would be the size of a pointer (4 bytes, on a 32 bit system).
0

Commented:
pls try this

sizeof(user);
0

Commented:
umangjoshi is correct
0

Associate Director - Product EngineeringCommented:
>> the second option gives me:

>> 'sizeof applied to incomplete type'

I think what daveyj1572 did was simply:

size_t s = sizeof(struct STRUCT_NAME);

size_t s = sizeof ( struct login ) ;

Mayank.

0

Commented:
ya mayank,
i think u r rite ... he must be using it like that.

daveyj1572
this is the complete code -

{
char time[10];
};

struct login user[5];//5 is the number of elements ..
//u can change it according to ur need

//this will give u the size of one element of type login

size_t s = sizeof(user);

//this will give u the size of the array user

I THING THIS IS PREETY CLEAR NOW ..

regards
ramesh

0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.