Having dynamically allocated an array , can I change its size?

Q

Having dynamically allocated an array , can I change its size?

✍: Guest

A

Yes. This is exactly what realloc is for. Given a region of malloced memory its size can be changed using code like:
dynarray = realloc(dynarray, 20 * sizeof(int));
Note that realloc may not always be able to enlarge memory regions in-place. When it is able to, it simply gives you back the same pointer you handed it, but if it must go to some other part of memory to find enough contiguous space, it will return a different pointer (and the previous pointer value will become unusable).
If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated.herefore, you usually don't want to immediately assign the new pointer to the old variable. Instead, use a temporary pointer:
#include <stdio.h> #include <stdlib.h>
int *newarray = (int *)realloc((void *)dynarray, 20 * sizeof(int));
if(newarray != NULL)
dynarray = newarray;
else {
fprintf(stderr, "Can't reallocate memory\n");
/* dynarray remains allocated */
}

When reallocating memory, be careful if there are any other pointers lying around which point into (``alias'') that memory: if realloc must locate the new region somewhere else, those other pointers must also be adjusted. Here is a (contrived, and careless of malloc's return values) example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *p, *p2, *newp;
int tmpoffset;
p = malloc(10);
strcpy(p, "Hello,"); /* p is a string */
p2 = strchr(p, ','); /* p2 points into that string */

tmpoffset = p2 - p;
newp = realloc(p, 20);
if(newp != NULL) {
p = newp; /* p may have moved */
p2 = p + tmpoffset; /* relocate p2 as well */
strcpy(p2, ", world!");
}

printf("%s\n", p);

(It is safest to recompute pointers based on offsets, as in the code fragment above. The alternative--relocating pointers based on the difference, newp - p, between the base pointer's value before and after the realloc--is not guaranteed to work, because pointer subtraction is only defined when performed on pointers into the same object.

2016-03-21, 1253👍, 0💬