-1

Is there any way to find the structure size dynamically in C??

Sizeof is compile time operator.. so what's the other option.

If we can have dynamically allocated array(flexible arrays) in a structure, then finding the structure size dynamically should also be there.. Plz help me out...

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Siri
  • 29
  • 1
  • 5
  • 3
    This is not clear, when you say `dynamically allocated array in a structure`, you mean the structure contains a pointer or do you mean flexible array members, etc...? Posting code would help. – Shafik Yaghmour Apr 28 '14 at 11:56
  • I think you'll have to know about the dynamically sized array in your code that needs the sizeof and do the calculation yourself - sorry. – Rup Apr 28 '14 at 11:56
  • We can see in my [answer here](http://stackoverflow.com/questions/20221012/unsized-array-declaration-in-a-struct/20221073#20221073) on how to use flexible array members the C standard provides an example and it uses an explicit size member in the struct, although the example does not explain that but it is a strong hint that is the right way to do it. – Shafik Yaghmour Apr 28 '14 at 13:14

3 Answers3

1

When you allocate an array dynamically in C, then you must remember its size too, if you wish to know the size of the array!

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

Structure sizes must be known at compile-time.

If it contains a pointer to dynamically allocated memory then that memory is not part of the struct - it's outside the struct and the pointer is pointing at it - so it does not affect the sizeof the struct.

If you're talking about flexible array member then you will need to implement your own way of knowing how much memory you allocated, e.g. have a struct member variable that holds the size.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Yea Sorry it's flexible array member... K thank u... k lemme write the code and post for it.. – Siri Apr 28 '14 at 12:32
  • You have to remember it, it's very similar to how you would remember how much memory you `malloc`'d in other situations. – M.M Apr 28 '14 at 12:33
1

sizeof's results are compile time constant as a the size of a variable or structure does not change during run-time.

The only exception to this are V(ariable)L(ength)Arrays for which the code defnding them "knows" the size.

Referring:

we can have dynamically allocated array in a structure

So let's assume:

struct s
{
  size_t size;
  int * ints;
}

The size is sizeof(struct s). That is the sum of

  • the size of an unsigned interger: sizeof(size_t)
  • the size of a pointer to int: sizeof (int *)
  • some optional padding bytes

This is independed of to how many bytes the structure's member int * ints may point.

alk
  • 69,737
  • 10
  • 105
  • 255