Can you resize a array in C without losing the data of the array with the previous size?
malloc() puts your data in heap memory but every time you call malloc() it chooses as a starting position a different position in heap memory
CodePudding user response:
In the general case, that is not always possible, as there maybe no room to expand at that memory location. There is a CRT function called realloc
which either expands in-place, or allocates new buffer and moves all your data there. Here's how you use it:
#include <stdio.h>
#include <stdlib.h>
int main() {
void* p = malloc(10);
if (!p) {
puts("Failed to allocate 10 bytes.");
return 0;
}
puts("Allocated 10 bytes");
void* tmp = realloc(p, 15);
if (!tmp) {
puts("Failed to allocate more memory");
free(p); // if allocation fails, you need to free the old buffer
return 0;
}
puts("Allocated 15 bytes");
if (tmp == p) {
puts("Start pointer still same");
}
// if allocation succeeds with realloc,
// you only need to free the new buffer
// even if expansion was not in-place.
free(tmp);
}
See the documentation.