Expand an array with realloc inside of a function

2019-06-14 05:43发布

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条回答
等我变得足够好
2楼-- · 2019-06-14 05:51
int MyFunction(people **record);// MyFunction(&record);//call at main
...

struct people *tmp = realloc(*record, 20 * sizeof (people));
if (tmp)
{
    *record = tmp;
}
查看更多
登录 后发表回答