As direct answer to your question, try
#include <stdio.h>
#include <stdlib.h>
struct Foo
{
int * p;
};
int main()
{
const size_t ITEMS = 10;
struct Foo foo;
foo.p = (int*) malloc( sizeof(int) * ITEMS);
printf("%p\n", foo.p);
size_t n;
for (n = 0; n<ITEMS; ++n)
foo.p[n] = n*n;
for (n = 0; n<ITEMS; ++n)
printf("foo.p[%lu]=%d\n", n, foo.p[n]);
free(foo.p);
return 0;
}
Anyway, note that, as
Sandeep Mewara suggested, the 'dynamic array' in the
struct
it is frequently accompained by another member indicating the size of the array itself. This is useful when passing the
struct
as argument to a function. For instance:
#include <stdio.h>
#include <stdlib.h>
struct DynArray
{
size_t items;
int *p;
};
void print_dynarray(struct DynArray da)
{
size_t n;
for (n = 0; n < da.items; ++n)
printf("item[%lu] = %d\n", n, da.p[n]);
}
int main()
{
const size_t ITEMS = 10;
struct DynArray da;
da.items = ITEMS;
da.p = (int*) malloc( sizeof(int) * da.items);
size_t n;
for (n = 0; n<ITEMS; ++n)
da.p[n] = n*n;
print_dynarray( da );
free(da.p);
da.items = 0;
return 0;
}