Zero said:
If we have a structure like:
struct something{
int *a;
int b;
};
We allocate mempry for a using malloc or calloc. The question is when
we want to know the size of the structure, sizeof(struct something),
it will not give us the correct number (i.e. the size of the structure
+ the size of the meory allacated). How do we get the "correct" size
of the structure?
I think you really want the correct size or count of the allocations,
not the total structure size.
You will need to to keep track of allocations you make for the pointer
a. I find it best to put a counter along with the pointer to the
array in a datatype. To access the data members you would use functions
that will increment the counter on allocations and decrement the counter
on deallocations. Using only the functions to modify the datatype will
help insure that the count will not get out of sync with the actual
allocations.
Example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXNAME 30
typedef struct NAMES
{
char (*name)[MAXNAME+1];
size_t num_names;
}NAMES;
char *addNAME(NAMES *p, const char *name);
void freeNAMES(NAMES *p);
int main(void)
{
NAMES president = {NULL};
size_t i;
addNAME(&president,"George Washington");
addNAME(&president,"Bill Clinton");
addNAME(&president,"George Bush");
for(i = 0;i < president.num_names;i++)
printf("president.name[%u] = %s\n",i,president.name
);
printf("The size of the array is: %u\n",
(sizeof *president.name)*president.num_names);
freeNAMES(&president);
printf("After deallocation, the array size is %u\n",
(sizeof *president.name)*president.num_names);
return 0;
}
char *addNAME(NAMES *p, const char *name)
{
char (*tmp)[MAXNAME+1];
tmp = realloc(p->name,(p->num_names+1)*(sizeof *tmp));
if(tmp == NULL) return NULL;
p->name = tmp;
strncpy(p->name[p->num_names],name,MAXNAME);
p->name[p->num_names][MAXNAME] = '\0';
return tmp[p->num_names++];
}
void freeNAMES(NAMES *p)
{
free(p->name);
p->name = NULL;
p->num_names = 0;
}