gpt4 book ai didi

C函数创建动态结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:21 25 4
gpt4 key购买 nike

有人可以帮助处理这段代码吗?为了简短起见,我省略了分配检查。

typedef struct {
int x;
int y;
} MYSTRUCT;

void init(MYSTRUCT **p_point);
void plusOne(MYSTRUCT **p_point, int *p_size);

int main()
{
MYSTRUCT *point;
int size = 1;

init(&point);

plusOne(&point, &size);
plusOne(&point, &size);

point[1]->x = 47; // this was the problem
point[1].x = 47; // this is solution

return 0;
}

void init(MYSTRUCT **p_point)
{
*p_point = (MYSTRUCT *) malloc( sizeof(MYSTRUCT) );
}

void plusOne(MYSTRUCT **p_point, int *p_size)
{
(*p_size)++;

*p_point = realloc(*p_point, *p_size * sizeof(MYSTRUCT) ); // also calling to the function is fixed
}

我不明白为什么调用函数后索引符号不起作用。

最佳答案

这是因为在 realloc 的调用中,您没有将 p_size 乘以 sizeof(MYSTRUCT),也没有将结果分配回去到p_point:

*p_point = realloc(*p_point, *p_size * sizeof(MYSTRUCT));

注意事项:

  • 您不需要在 C 中转换 mallocrealloc 的结果。
  • 为了保持一致性,考虑将 &size 传递给 init,并在那里将其设置为 1

关于C函数创建动态结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23787417/

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