Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c - How to declare a pointer to an array of pointer

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));
        }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...