Categories:
.NET (357)
C (330)
C++ (184)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (2)
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, 1819👍, 0💬
Popular Posts:
How do we host a WCF service in IIS? Note: - The best to know how to host a WCF in IIS is by doing a...
Can event’s have access modifiers ? Event’s are always public as they are meant to serve every one r...
What is the difference between Class and structure’s ? Following are the key differences between the...
Can Multiple Cursors Being Opened at the Same Time? - Oracle DBA FAQ - Working with Cursors in PL/SQ...
How To Test Transaction Isolation Levels? - MySQL FAQs - Transaction Management: Commit or Rollback ...