Well, as the other answers have explained nicely about the reason for using vectors, I will simply elaborate on why realloc
was not implemented. For this, you need to take a look at what realloc
actually does. It increases the size of the memory by intelligently using malloc()
and free()
. You need to understand, that though it seems to simply increase the size, it does not actually increase the size, but instead allocates another block of memory with the required size (That explains the name realloc
).
Take a look at the following lines:
int* iarr = (int*)malloc(sizeof(iarr)*5);
iarr = (int*)realloc(6,sizeof(iarr)); //this is completely discouraged
//what you're supposed to do here is:
int* iarr2 = (int*)realloc(iarr,1 + sizeof(iarr)); //copies the old data to new block implicitly
//this not only saves the previous state, but also allows you to check if realloc succeeded
In C++, this can be (if it is must) achieved, by writing:
int* iarr = new int[5];
int* iarr2 = new int[6];
for(int i = 0; i < 5; i++) {
iarr2[i] = iarr[i];
}
delete[] iarr;
The only use of realloc
was to increase the memory capacity; as C arrays
did not do that automatically they had to provide a mechanism to do so; which has been implicitly implemented in most of the containers
, making the reason for having a realloc
in the first place, moot.