扩大与realloc的数组的函数内 - 指针? [英] Expand an array with realloc inside of a function - Pointers?

查看:120
本文介绍了扩大与realloc的数组的函数内 - 指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这个问题的答案是我不理解指针和引用正确!

因此​​,在我的C文件的开头,我定义为一个结构的个人

  typedef结构{
    炭编号[4];
    INT年龄;
    CHAR名称[128];
}人;

然后里面的main()创建的10 结构数组名为记录

 人*记录=(人*)malloc的(sizeof的(人)* 10);

在main()中,我们开始,然后纵身跳下与功能

  MyFunction的(记录);

(此功能是在之前的C文件的开头原型主()以

  INT MyFunction的(人*记录);

里面的MyFunction(),我们做各种各样的东西,包括希望增加在记录数组的大小,以便它可以容纳更多的个人结构。
我试图增加在记录数组大小

 结构*人TMP = realloc的(记录,20 * sizeof的(人));
如果(TMP)
{
    记录= tmp目录;
}

但是,这并不工作,我得到的内存损坏,如果我尝试使用新添加的结构数组中的

正如我所说的,我敢肯定,这是由于我没有低估指针和引用正确。
请注意,我不能有MyFunction的(),因为我已经在使用它的返回INT别的东西给一个扩大的记录数组作为它的返回类型(我不知道我会得到正常工作或者) - !我需要它使用的主要的记录阵列为

任何人都可以点我朝着正确的方向吗?


解决方案

  INT MyFunction的(人**记录); // MyFunction的(安培;记录); //调用在主
...结构*人TMP = realloc的(*记录,20 * sizeof的(人));
如果(TMP)
{
    *记录= tmp目录;
}

I'm sure that the answer to this is me not understanding Pointers and References properly!

So at the start of my C file I define a struct for people:

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

Then inside of main() I create an array of 10 people structs called record.

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

In main() we start and then dive off into a function with

MyFunction(record);

(This function is prototyped at the beginning of the C file before main() with

int MyFunction(people *record);

Inside of MyFunction() we do various stuff, including wanting to increase the record array size so that it can hold more people structs. I'm attempting to increase the record array size with

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

But this doesn't work and I get memory corruption if I attempt to use the newly added structs in the array.

As I said, I'm sure that this is due to me not understating Pointers and References properly. Note that I can't have MyFunction() give an expanded record array as its return type because I'm already using its return int for something else (and I'm not sure I'd get that to work properly either!) - I need it to be using the main record array.

Can anyone point me in the right direction please?

解决方案

int MyFunction(people **record);// MyFunction(&record);//call at main
...

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

这篇关于扩大与realloc的数组的函数内 - 指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆