-2

I have a task to create an array of pointers to structure. I need to use just void functions and "malloc". I have no idea how to do it, could you help me?

void create1(apteka*** a, int size)
{
    **a = (apteka**) malloc(size* sizeof(apteka*));
        for (int i = 0; i < size; i++)
        {
            x[0][i] = (apteka*)malloc(size * sizeof(apteka));
        }
}
alk
  • 69,737
  • 10
  • 105
  • 255
user76234
  • 43
  • 1
  • 5
  • `*a` instead of `*aa` - `*a = (apteka**) malloc(size* sizeof(apteka*));`? – Rabbid76 Oct 14 '18 at 10:10
  • 2
    One of the many reasons you use pointed-to variable sizes with `sizeof`. Ex: `*a = malloc(size * sizeof **a);` And I have no earthly idea what `x` is in this. And as usual, [don't cast `malloc` results in C programs](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Oct 14 '18 at 10:15
  • 1
    sorry, it should be "a" of course, i forgot about it, thank you – user76234 Oct 14 '18 at 10:17
  • 1
    No need to cast `void`-pointers in C. `malloc()` returns a `void`-pointer, so just drop the cast. – alk Oct 14 '18 at 10:18

1 Answers1

1

I have a task to create an array of pointers to structure

You need two "sizes":

  1. The number of pointers
  2. 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\n", 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);
}
alk
  • 69,737
  • 10
  • 105
  • 255