Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Having dynamically allocated an array , can I change its size?
Having dynamically allocated an array , can I change its size?
✍: Guest
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, 1079👍, 0💬
Popular Posts:
What is the version information in XML? “version” tag shows which version of XML is used.
If we inherit a class do the private variables also get inherited ? Yes, the variables are inherited...
What is a delegate ? Delegate is a class that can hold a reference to a method or a function. Delega...
How To Set Background to Transparent or Non-transparent? - CSS Tutorials - HTML Formatting Model: Bl...
Can you explain different software development life cycles -part II? Water Fall Model This is the ol...