-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));
        }
}
4
  • *a instead of *aa - *a = (apteka**) malloc(size* sizeof(apteka*));? Commented Oct 14, 2018 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. Commented Oct 14, 2018 at 10:15
  • 1
    sorry, it should be "a" of course, i forgot about it, thank you Commented Oct 14, 2018 at 10:17
  • 1
    No need to cast void-pointers in C. malloc() returns a void-pointer, so just drop the cast. Commented Oct 14, 2018 at 10:18

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.