memory management - How can I get the size of an array from a pointer in C? -


i've allocated "array" of mystruct of size n this:

if (null == (p = calloc(sizeof(struct mystruct) * n,1))) {  /* handle error */ } 

later on, have access p, , no longer have n. there way determine length of array given pointer p?

i figure must possible, since free(p) that. know malloc() keeps track of how memory has allocated, , that's why knows length; perhaps there way query information? like...

int length = askmalloclibraryhowmuchmemorywasalloced(p) / sizeof(mystruct) 

i know should rework code know n, i'd rather not if possible. ideas?

no, there no way information without depending on implementation details of malloc. in particular, malloc may allocate more bytes request (e.g. efficiency in particular memory architecture). better redesign code keep track of n explicitly. alternative at least redesign , more dangerous approach (given it's non-standard, abuses semantics of pointers, , maintenance nightmare come after you): store lengthn @ malloc'd address, followed array. allocation be:

void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1)); *((unsigned long int*)p) = n; 

n stored @ *((unsigned long int*)p) , start of array now

void *arr = p+sizeof(unsigned long int); 

edit: play devil's advocate... know these "solutions" require redesigns, let's play out. of course, solution presented above hacky implementation of (well-packed) struct. might define:

typedef struct {    unsigned int n;   void *arr; } arrinfo; 

and pass around arrinfos rather raw pointers.

now we're cooking. long you're redesigning, why stop here? want abstract data type (adt). introductory text algorithms , data structures class it. adt defines public interface of data type hides implementation of data type. thus, publicly adt array might like

typedef void* arrayinfo; (arrayinfo)newarrayinfo(unsignd int n, unsigned int itemsize); (void)deletearrayinfo(arrayinfo); (unsigned int)arraylength(arrayinfo); (void*)arrayptr(arrayinfo); ... 

in other words, adt form of data , behavior encapsulation... in other words, it's close can object-oriented programming using straight c. unless you're stuck on platform doesn't have c++ compiler, might go whole hog , use stl std::vector.

there, we've taken simple question c , ended @ c++. god all.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -