How to determine the size of dynamical arrays?

R

Richard Heathfield

FraterQ wrote:

But I've the following problem: I can't determine the size of the
dynamical generated array through a predefined function like sizeof().
Can anybody explain, how to get the reserved memorysize?

When you allocate the memory, you know how much you're allocating.

Don't Forget.
 
E

Emmanuel Delahaye

In said:
Hello,

after i've read this post, i tried it myself and it works.
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&threadm=9jjh9
m%247bb%242%40oravannahka.helsinki.fi&rnum=1&prev=/groups%3Fhl%3Den%26lr%
3D%26ie%3DUTF-8%26oe%3Dutf-8%26q%3Dresize%2Barray%2Bc%2Brealloc%26btnG%3D
Google%2BSearch But I've the following problem: I can't determine the
size of the dynamical generated array through a predefined function like
sizeof(). Can anybody explain, how to get the reserved memorysize?

Ask the one who has allocated the memory block to keep the size in some
memory. A common tip is the following :

typedef struct
{
int *a; /* dynamic array of int */
size_t n;
}
buf_s;

buf_s buf;

buf_create (&buf, 123);

with

int buf_create (buf_s * this, size_t n)
{
err = 1;

if (this)
{
this->a = NULL;
this->n = 0;

{
int *p = malloc (sizeof *p * n); /* <stdlib.h> */

if (p)
{
this->a = p;
this->n = n;
err = 0;
}
}
}
return err;
}
 
M

Martin Ambuhl

(e-mail address removed) (FraterQ) wrote (02 Jul 2003) in
/ comp.lang.c:
Hello,

after i've read this post, i tried it myself and it works.
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=utf-8&threadm
=9jjh9m%247bb%242%40oravannahka.helsinki.fi&rnum=1&prev=/groups%3Fh
l%3Den%26lr%3D%26ie%3DUTF-8%26oe%3Dutf-8%26q%3Dresize%2Barray%2Bc%2
Brealloc%26btnG%3DGoogle%2BSearch But I've the following problem:
I can't determine the size of the dynamical generated array
through a predefined function like sizeof(). Can anybody explain,
how to get the reserved memorysize?

Remember it, for goodness' sake! You can't dynamically create
without having the size information; why do you throw away what you
already know?
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top