gpt4 book ai didi

c - 指向指针数组的指针与指向数组的指针

转载 作者:行者123 更新时间:2023-12-02 02:47:46 24 4
gpt4 key购买 nike

我得到了一个创建 box_t ** 的 .o 文件,我必须使用它。现在不知道是不是案例 1:
指向 box_t 或
数组的指针案例 2:
指向 box_t 数组的指针 *

我自己编写了一个简单的代码来创建 box_t** 以两种方式和不同的访问方式。在这两种情况下它似乎都工作正常。现在,给定一个 box_t ** 和 size_t n,其中的元素数量,是否可以在没有任何进一步信息的情况下知道它是情况 1 还是情况 2。

struct box_tag{
int pencils;
int pens;
};

typedef struct box_tag box_t;

box_t boxarray[10] = {{1,2},{3,4},
{5,6},{7,8},
{9,10},{11,12},
{13,14},{15,16},
{17,18},{19,20}};

box_t ** box_bundle;

创建版本 1:

box_t** create_dp(void)
{
box_bundle = (box_t **)malloc(sizeof(box_t **));
*box_bundle = boxarray;
}

访问版本 1:

int main ()
{
box_t * tmp = *box_bundle;

for (int i =0; i<10; i++)
{
printf("%d\n",tmp[i].pencils);
}

return 0;
}

创作版本 2:

box_t** create_dp (void)
{
box_bundle = (box_t **)malloc(sizeof(box_t **));
*box_bundle = (box_t *)malloc (sizeof(box_t *) * 10);

for(int i=0; i<10;i++)
{
*(box_bundle +i ) = &boxarray[i];
}
}

访问版本 2:

int main ()
{
create_dp();

for(int i=0; i<10; i++)
{
box_t * tmp =*box_bundle++;
printf("pencils %d \n", tmp->pencils);
}

return 0;
}

最佳答案

两种情况都不正确。您不能使用 box_t** 指向任何数组。它也不能指向 box_t boxarray[10] 类型的数组,因为它们是不兼容的类型。您的代码中的任何地方都不需要多个间接级别。

但是您可以使用 box_t* 指向数组中的第一个元素,这就是您的代码在此处所做的:*box_bundle = boxarray;。但是以一种模糊的方式。

正确的代码应该是:box_t* box_bundle;。如果它应该指向原始数组,则不需要 malloc。如果它应该保存原始数组的副本,则需要分配和复制数据:

box_t* box_bundle = malloc (sizeof(*box_bundle)*10);
memcpy(box_bundle, boxarray, sizeof boxarray);

关于c - 指向指针数组的指针与指向数组的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53630035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com