Angus said:
Hello
If I do this:
struct mystruct
{
long nKey;
char szItem[20];
};
long numitemstocreate = GetItems();
struct mystruct* devlist = (mystruct*)malloc(numlines * sizeof(mystruct));
// Then populate some values
Now I want to find number of array elements - ie get numitemstocreate. 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(mystructArr *p,long key, const char *s);
void FreeElements(mystructArr *p);
int main(void)
{
mystructArr names = {NULL,0};
size_t i;
AddElement(&names,7L,"George Washington");
AddElement(&names,45L, "George Bush");
puts("The array contents");
for(i = 0; i < names.size;i++)
printf("names.element[%u].szItem = \"%s\"\n"
"names.element[%u].nKey = %ld\n\n",i,
names.element
.szItem,i, names.element.nKey);
FreeElements(&names);
return 0;
}
mystruct *AddElement(mystructArr *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(mystructArr *p)
{
if(p)
{
free(p->element);
p->element = NULL;
p->size = 0;
}
return;
}