Realloc is not resizing array of pointers

后端 未结 2 1290
死守一世寂寞
死守一世寂寞 2020-12-21 15:45

I keep passing in and returning the dirs_later_array. When I get to \"new_size=...\" in the else block, I end up with new_size of 2 the second time around. So far so good.

相关标签:
2条回答
  • 2020-12-21 16:19

    Your sizeof(struct dirs_later*) should be changed to sizeof(struct dirs_later) - as before!

    Also the sizeof is a compile time feature. You need a structure like this to hold the size

    struct my_dirs
       struct dirs_later *dirs;
       int size;
    };
    

    Initialise it like this

    struct my_dirs directories;
    directories.size = 0;
    directories.dirs = NULL;
    

    Then to add (note realloc can take NULL as a parameter

    directories.dirs = realloc(directories.dirs,
                               (++directories.size) * sizeof(struct dirs_later));
    

    This would also simplify your code.

    0 讨论(0)
  • 2020-12-21 16:25

    Operator sizeof is a compile time feature and it only checks the static size of an expression. So for pointer it only returns the size of that pointer which is 4 on your platform. sizeof does not measure the size of a dynamically allocated data. There is no standard feature in C to get the size of dynamically allocated data.

    0 讨论(0)
提交回复
热议问题