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, 1644👍, 0💬
Popular Posts:
Describe different elements in Static Chart diagrams ? Package: - It logically groups element of a U...
How to measure functional software requirement specification (SRS) documents? Well, we need to defin...
How does one iterate through items and records in a specified block? One can use NEXT_FIELD to itera...
What are the two kinds of comments in JSP and what's the difference between them? <%-- JSP Co...
How To Escape Special Characters in SQL statements? - MySQL FAQs - Introduction to SQL Basics There ...