Initially mallocate 0 elements to later reallocate and measure size

此生再无相见时 提交于 2019-12-02 04:56:08

问题


I have a function that will add a new position to an array by reallocating new memory every time it is called.

The problem is that, for each call I need it to add one position to the array, starting from 1 at first call, but I understand that I have to mallocate before reallocating.

So my question is, can I initially do something like p = malloc(0) and then reallocate for example using p = (int *)realloc(p,sizeof(int)) inside my function? p is declared as int *p.

Maybe with a different syntax?

Of course I could make a condition in my function that would mallocate if memory hasn't been allocated before and reallocate if it has, but I am looking for a better way.

And the second problem I have is... Once reallocated more positions, I want to know the size of the array.

I know that if, for example, I declare an array a[10], the number of elements would be defined by sizeof(a)/sizeof(a[0]), but for some reason that doesn't work with arrays declared as pointers and then reallocated.

Any advice?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/30688800/initially-mallocate-0-elements-to-later-reallocate-and-measure-size

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