Solved

# Without using sizeof how do i calculte structure size

Posted on 2008-06-11
606 Views
Hi,
I have one structure having two int and a char. how do i calculate size of the structure?
thanks,
santanu
0
Question by:arijit_rebaca
• 4
• 2
• 2

LVL 40

Expert Comment

>> I have one structure having two int and a char.
The size of these is platform dependent (their size isn't defined in the standard)

>> how do i calculate size of the structure?
At best you can approximate it, by adding together the (assumed) size of the types it aggregates but structs can also contain padding and unless you also know how this has been implemented you'll not necessarily get the right result. In other words the sum of the parts might be less than the whole.
0

LVL 53

Expert Comment

sizeof is the easiest way :

typedef struct Test {
int i;
char c;
} Test;

sizeof(Test);

Other methods will not be reliable due to padding that might be added to the struct.
0

LVL 53

Expert Comment

Any reason you don't want to use sizeof ?
0

LVL 40

Expert Comment

0

LVL 10

Accepted Solution

peetm earned 125 total points
#include <stdio.h>

int main(void)
{
struct thing
{
int     a;
char    b;
float   c;
};

struct thing t;

struct thing * ptr = &t;

printf("%u\n", (char *)(ptr + 1) - (char *)ptr);

return 0;
}
0

LVL 53

Expert Comment

>> (char *)(ptr + 1)

Hehe ... that's cheating lol ... But true : sizeof is not used explicitly.
0

LVL 10

Expert Comment

>>Hehe ... that's cheating lol ... But true : sizeof is not used explicitly.

:-)

And, one would not of course want to have a struct larger than ptrdiff_t, and, I'm not so sure about using 'u' either - still I reckon it's the kind of thing that someone's got in mind here.
0

LVL 53

Expert Comment

>> still I reckon it's the kind of thing that someone's got in mind here.

There's a good chance of that :)
0

## Featured Post

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.