0

I have a c struct defined as follows:

typedef struct
{
    int data_size;          
    BYTE* data;
} IMAGE;

I have another struct like this

typedef struct
{
    int nimages;
    IMAGE* images;
} IMGARR

I would like to be able to reallocate images to hold another sizeof(IMAGE) structure so I can just keep an array of images with their binary data.

Here is what I've been trying

IMGARR* image_temp = imgarr->images; //store pointer
image_temp = realloc(&image_temp, (imgarr->nimages + 1) * sizeof(IMAGE)); //realloc memory
memcpy(&imgarr->images[imgarr->nimages], &my_new_image, sizeof(IMAGE));

This doesn't seem to work at all. I seem to have become really rusty at c memory allocation. Any help would be awesome!

2
  • Your use of types and variable names is a little bit confusing. Is imgarr of type IMGARR*? Is imgarr-images of type IMAGE*? Commented Dec 24, 2014 at 3:48
  • that is pretty confusing I see that now. I think I have fixed my problem, I'll post an update when I'm able to confirm. Commented Dec 24, 2014 at 4:51

2 Answers 2

1

Right way to do this is:

IMGARR* image_temp = realloc(imgarr->images, (n+1) * sizeof(IMAGE)); /* n = New size */
if(image_temp != NULL)
imgarr->images = image_temp;
Sign up to request clarification or add additional context in comments.

Comments

0

You've not changed what imgarr->images points to. Check image_temp for NULL but if you got the space then reassign ->images before attempting to write to it.

Also, no need for the memcpy. Direct assignments of structs is allowed.

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.