【问题标题】:Expand an array with realloc inside of a function - Pointers?在函数内部使用 realloc 扩展数组 - 指针?
【发布时间】:2014-10-14 18:42:19
【问题描述】:

我确定这个问题的答案是我没有正确理解指针和引用!

所以在我的 C 文件的开头,我为 people 定义了一个结构:

typedef struct {
    char id[4];
    int age;
    char name[128];
} people;

然后在 main() 内部创建一个由 10 个 people 结构组成的数组,称为 record

people* record = (people*)malloc(sizeof(people)* 10);

在 main() 中,我们开始然后进入一个函数

MyFunction(record);

(这个函数原型在main()之前的C文件开头用

int MyFunction(people *record);

在 MyFunction() 内部,我们做了很多事情,包括想要增加 record 数组的大小,以便它可以容纳更多的 people 结构。 我正在尝试使用

增加 record 数组大小
struct people *tmp = realloc(record, 20 * sizeof (people));
if (tmp)
{
    record = tmp;
}

但这不起作用,如果我尝试使用数组中新添加的结构,我会遇到内存损坏。

正如我所说,我确信这是因为我没有正确地低估指针和引用。 请注意,我不能让 MyFunction() 将扩展的 record 数组作为其返回类型,因为我已经将它的 return int 用于其他东西(而且我不确定我会得到那个也可以正常工作!) - 我需要它使用主 record 数组。

谁能指点我正确的方向?

【问题讨论】:

  • 您传递的是记录的地址而不是指针的地址。即使被调用函数已经将记录移动到新分配的地址范围,调用函数仍将记录的旧地址分配给旧指针。

标签: c arrays pointers struct realloc


【解决方案1】:
int MyFunction(people **record);// MyFunction(&record);//call at main
...

struct people *tmp = realloc(*record, 20 * sizeof (people));
if (tmp)
{
    *record = tmp;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 2013-02-11
    • 2013-06-11
    • 2016-04-09
    • 1970-01-01
    • 2021-10-14
    • 2016-05-16
    • 1970-01-01
    相关资源
    最近更新 更多