创建一个包含指针的数组

标签 c arrays pointers malloc

我试图在 C 中创建一个指针数组。数组的每个值都应该是一个指向结构的指针(我们称它为 struct Type*)。

我应该怎么做

struct Type* myVariable= malloc(sizeof(struct Type*)*MY_SIZE);

struct Type** myVariable= malloc(sizeof(struct Type*)*MY_SIZE);

第二个看起来像我想创建一个二维数组时应该做的,它是一个指针数组,这些指针用于创建所需类型的数组。 编辑:但在我的例子中,第二维大小只有一个

第一个看起来像一个常规数组,其包含的值类型为 int*。

我如何将好的解决方案传递给一个函数(通过指针,而不是通过值,因为数组可能相当大)并在函数中使用它?

最佳答案

第二个正确的解决方案。但是,您也需要为对象分配内存。此外,请务必检查 malloc 返回的值。

// Allocate memory for the array of pointers.
struct Type** myVariable = malloc(sizeof(struct Type*)*MY_SIZE);
if ( myVariable == NULL )
{
   // Deal with error
   exit(1);
}

for (int i = 0; i < MY_SIZE; ++i )
{
   // Allocate memory for the array of objects.
   myVariable[i] = malloc(sizeof(struct Type)*THE_SIZE_IN_THE_OTHER_DIMENSION);
   if ( myVariable[i] == NULL )
   {
      // Free everything that was allocated so far
      for (int j = 0; j < i-1; ++j )
      {
         free(myVariable[j]);
      }
      free(myVariable);

      // Exit the program.
      exit(1);
   }
}

但是,如果 THE_SIZE_IN_THE_OTHER_DIMENSION 将是 1,您最好使用第一种方法。

struct Type* myVariable = malloc(sizeof(struct Type)*MY_SIZE);
                                     // ^^^^^^^^^^^ Drop the *
if ( myVariable == NULL )
{
   // Deal with error
   exit(1);
}

关于创建一个包含指针的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299508/

相关文章:

c - 理解 C : Pointers and Structs

pointers - 在 Go 中传递任意 slice

c - 设置孪生指针的最有效算法

python - 如何使用 Python.h 文件来制作 python C 扩展

c - 第二次编译时getch未定义

javascript - 为什么这个数组未定义?

javascript - axios 和 promises,数组值不可用但出现在 console.log 中

c - 我正在尝试使用 malloc 函数为数组分配内存,但值未正确扫描。谁能解释一下吗?

c - 条件评估为有符号或无符号整数?

java - Java实现多维数据的高效方法