0

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?

Westyfield2
  • 83
  • 1
  • 1
  • 5
  • 1
    You are passing the address of the record not the address of the pointer. The calling function still has the old address of the record assigned to the old pointer even though the called function already moved the record to the newly allocated address range. – alvits Oct 14 '14 at 19:09

1 Answers1

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

struct people *tmp = realloc(*record, 20 * sizeof (people));
if (tmp)
{
    *record = tmp;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70