首页 > 解决方案 > 最佳实践方法,在库中创建指向 typdef 的指针数组,并将其指针传递给其他源模块

问题描述

我正在创建一个库。需要从 init 函数返回指向 typdef 的顶级关键指针数组。做这个的最好方式是什么?

是否在 Init 函数之外创建数组,...并在其他源模块中将其声明为 extern?

myType *myArray[256];

void Init()
{
  // seed the 1st element.
  myArray[0] = malloc(sizeof(myType));

  // initialize some variables in the 1st myType.
}

...还是我在 Init 中完成所有操作:

// library.c
void *Init()
{
  static myType *myArray[256];

  // seed the 1st element.
  myArray[0] = malloc(sizeof(myType));

  // initialize some variables in the 1st myType.

  return myArray;
}

// main.c
extern myType *myArray[256];

int main ()
{
   myArray = Init();
}

……或者完全是别的什么?

谢谢!

标签: carrayspointersstaticparameter-passing

解决方案


推荐阅读