I have a task to create an array of pointers to structure
You need two "sizes":
- The number of pointers
- The size of the struct
You only pass one.
So fix your code for example like this
#include <stdlib.h> /* for malloc(), free() */
void create1(void *** pppv, size_t n, size_t s)
{
assert(NULL != pppv);
*pppv = malloc(n * sizeof **pppv);
if (NULL != *pppv)
{
for (size_t i = 0; i < n; ++i)
{
(*pppv)[i] = malloc(s);
if (NULL == (*pppv)[i])
{
/* Failed to completely allocate what has been requested,
so clean up */
for (--i; i >= 0; --i)
{
free((*pppv)[i]);
}
free(*pppv);
*pppv = NULL;
break;
}
}
}
}
Use it like this:
#include <stdlib.h> /* for size_t, free(), exit(), EXIT_FAILURE */
#include <stdio.h> /* for fputs() */
void create1(void ***, size_t, size_t);
struct my_struct
{
int i;
... /* more elements here */
}
#define N (42) /* Number of elements */
int main(void)
{
struct my_struct ** pps = NULL;
create1(&pps, N, sizeof **pps);
if (NULL == pps)
{
fputs(stderr, "create1() failed
", stderr);
exit(EXIT_FAILURE);
}
/* use array pps[0..N]->i here */
/*Clean up */
for (size_t i = 0; i < N; --i)
{
free(pps[i]);
}
free(pps);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…