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?

1
  • 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. Commented Oct 14, 2014 at 19:09

1 Answer 1

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

struct people *tmp = realloc(*record, 20 * sizeof (people));
if (tmp)
{
    *record = tmp;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.