我试图在 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/