sizeof dynamic structure array

C

cerr

Hi There,

Let's say I have a structure array that changes its size (elements in
array) with realloc().
Is there a possibility for me to read how much memory is currently
allocated and how many elements are available or do i need to carry
the "number of elements" in a global variable forward?

Thank you,
Ron
 
P

Peter Nilsson

cerr said:
Let's say I have a structure array that changes its size
(elements in array) with realloc().
Is there a possibility for me to read how much memory is
currently allocated and how many elements are available
http://c-faq.com/malloc/querysize.html

or do i need to carry the "number of elements" in a
global variable forward?

Put it in the struct it pertains to.
 
S

Seebs

Let's say I have a structure array that changes its size (elements in
array) with realloc().
Is there a possibility for me to read how much memory is currently
allocated and how many elements are available or do i need to carry
the "number of elements" in a global variable forward?

You can't query how much is in use or how much is being used in general,
but I would recommend strongly against a global variable. You might consider
a struct:

struct many_foo {
int size;
int count;
foo *foos;
};

-s
 
S

Scooser

Hi,

if you don't like the layer of indirection you can also do it this way

struct many_foo {
size_t max;
size_t count;
foo foos[]
};

many_foo * ptr_to_foo = malloc ( sizeof (*ptr_to_foo ) + max *
sizeof (foo) );
if (ptr_to_foo)
{
ptr_to_foo->max = max;
ptr_to_foo->count = 0;
}

If you have to use a C90 compiler you'll have to a hack - violating
the standard - and add an array with one dummy object to the struct

struct many_foo {
size_t max;
size_t count;
foo foos[1]
};

many_foo * ptr_to_foo = malloc ( sizeof (*ptr_to_foo ) + (max - 1)
* sizeof (foo) );
if (ptr_to_foo)
{
ptr_to_foo->max = max;
ptr_to_foo->count = 0;
}


Scooser
 
B

Ben Bacarisse

Scooser said:
if you don't like the layer of indirection you can also do it this way

struct many_foo {
size_t max;
size_t count;
foo foos[]
};

many_foo * ptr_to_foo = malloc ( sizeof (*ptr_to_foo ) + max *
sizeof (foo) );

Small suggestion. You obviously like the

T *tp = malloc(sizeof *tp);

idiom so why not extend it to avoid accidental use of the wrong type
for the foos array?

many_foo *ptr_to_foo = malloc(sizeof *ptr_to_foo +
max * sizeof ptr_to_foo->foos[0]);

You don't get the same instant checkability (because the name of
flexible member is not evident in the declaration) but I think you get
a little more robustness to change this way.

<snip>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top