Initially mallocate 0 elements to later reallocate and measure size

◇◆丶佛笑我妖孽 提交于 2019-12-01 23:34:29

You could initialize your pointer to NULL, so that the first time you call realloc(yourPointer, yourSize), it will return the same value as malloc(yourSize).

For your second problem, you could use a struct that contains your pointer and a count member.

struct MyIntVector {
    int * ptr;
    size_t count;
}

Then you probably will want to define wrapper functions for malloc, realloc, and free (where you could reset ptr to NULL), that takes your struct as one of the parameters, and updates the struct as needed.

If you want to optimize this for pushing 1 element at a time, you could add a allocatedCount member, and only realloc if count == allocatedCount, with a new allocatedCount equals (for example) twice the old allocatedCount.

You should implement this in a MyIntVector_Push(MyIntVector *, int ) function.

You will then have a simplified c version of c++ std::vector<int> (but without automatic deallocation when the object goes out of scope).

As ThreeStarProgrammer57 said just use realloc.

realloc(NULL, nr_of_bytes) is equivalent to malloc(nr_of_bytes)

so

p = realloc(p, your_new_size) 

will work just fine the first time if p is initialized to NULL. But be sure to pass the number of bytes you need after resizing, not the additional space that you want, as you have written your question.

As regarding the size, you have to keep track of it. That's the way C was designed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!