Angus Comber wrote:
Hello
If I do this:
struct mystruct
{
long nKey;
char szItem[20];
};
long numitemstocreat e = GetItems();
struct mystruct* devlist = (mystruct*)mall oc(numlines * sizeof(mystruct ));
// Then populate some values
Now I want to find number of array elements - ie get numitemstocreat e. I
know I already have it - but may want to get again.
How do I get the number of array items?
typedef struct mystructArr
{
struct mystruct *element;
size_t size;
}mystructArr;
Declare and use a datatype that has a member that points to the array
and a member that keeps a count of the number of array elements allocate.
Example of use:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ITEMSZ 20
typedef struct mystruct
{
long nKey;
char szItem[ITEMSZ];
}mystruct;
typedef struct mystructArr
{
mystruct *element;
size_t size;
}mystructArr;
mystruct *AddElement(mys tructArr *p,long key, const char *s);
void FreeElements(my structArr *p);
int main(void)
{
mystructArr names = {NULL,0};
size_t i;
AddElement(&nam es,7L,"George Washington");
AddElement(&nam es,45L, "George Bush");
puts("The array contents");
for(i = 0; i < names.size;i++)
printf("names.e lement[%u].szItem = \"%s\"\n"
"names.elem ent[%u].nKey = %ld\n\n",i,
names.element[i].szItem,i, names.element[i].nKey);
FreeElements(&n ames);
return 0;
}
mystruct *AddElement(mys tructArr *p, long key, const char *s)
{
mystruct *tmp;
size_t cnt;
if( !p || ITEMSZ < 1) return NULL;
cnt = p->size;
if((tmp = realloc(p->element,(cnt+1 )*(sizeof *tmp))) == NULL)
return NULL;
p->element = tmp;
p->element[cnt].nKey = key;
strncpy(p->element[cnt].szItem, s, ITEMSZ);
p->element[cnt].szItem[ITEMSZ-1] = '\0';
p->size++;
return &p->element[cnt];
}
void FreeElements(my structArr *p)
{
if(p)
{
free(p->element);
p->element = NULL;
p->size = 0;
}
return;
}
--
Al Bowers
Tampa, Fl USA
mailto:
xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/