如何声明一个指向指针数组的指针 [英] How to declare a pointer to an array of pointer

查看:366
本文介绍了如何声明一个指向指针数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务来创建一个指向结构的指针数组.我只需要使用void函数和"malloc".我不知道该怎么做,你能帮我吗?

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

推荐答案

我有一个任务来创建指向结构的指针数组

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

您需要两个大小":

  1. 指针数
  2. 结构的大小

您只能通过一个.

因此,请像这样修复您的代码

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;
       }
    }
  }
}

像这样使用它:

#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);
}

这篇关于如何声明一个指向指针数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆