Expand an array with realloc inside of a function - Pointers?

天大地大妈咪最大 提交于 2019-12-08 11:43:01

问题


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?


回答1:


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

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


来源:https://stackoverflow.com/questions/26368022/expand-an-array-with-realloc-inside-of-a-function-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!