Search code examples
cstructurerealloc

realloc int pointer present in a structure [C]


I want to malloc an integer pointer present inside a structure.

If in future I need to expand the array, I use realloc.

something like this:

typedef struct {
   int *temp,count
}foo;

main()
{
    foo *fake = (foo*)malloc(1*sizeof(foo));
    fake.count = 0;

    ++(fake.count);
    fake.temp = (int*)malloc((fake.count)*sizeof(int));

    /* I do something */

    /*now i want to realloc "temp" to ++(fake.count) */

Is this way of doing that correct?

    ++(fake.count);
    fake.temp = (int*)realloc(fake.temp,(fake.count)*sizeof(int));

Solution

  • In principle, yes.

    However, you should make sure that your code survives possible errors in realloc, like so:

    int * p = realloc(fake->temp, (fake->count + 1) * sizeof(int));
    if (p) { fake->temp = p; ++fake->count; }
    else   { /* error! But fake was untouched. */ }
    

    Also, you should say int main(void) for your main function declaration. Finally, you shouldn't cast the result of malloc or realloc, since a void* is implicitly convertible to any other object pointer.

    One more: Your coding style is really difficult for others to read. I'd write the struct definition like this:

    typedef struct foo_
    {
        int * temp;
        int   count;
    } foo;
    

    And even one more: Do you need to allocate fake dynamically? If not, an automatic variable foo fake; may be easier to maintain. In any event, if you do want to allocate it dynamically, don't cast and don't repeat the type, like so:

    foo * fake = malloc(sizeof *fake);
    // or:       calloc(1, sizeof *fake);      // this will zero out the memory