Problem
C++里我NEW了一個CHAR[10] 後來發現不購大 想加大空間 而不損害原來的內容怎麽辦?Solution使用realloc()重新配置記憶體大小,類似VB的redim()。header : stdlib.hsignature : void* realloc(void* pmem, size_t size);pmem : 一個pointer,指向已經配置出去的記憶體區塊size : 新的記憶體空間大小(byte)Sample Code /**//* (C) OOMusou 2007 http://oomusou.cnblogs.comFilename : realloc.cppCompiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++Description : Demo how to reallocate charRelease : 05/26/2007 1.0*/#include "stdio.h"#include "stdlib.h"#include "string.h"int main() { char* s = (char*)malloc(11); memset(s, 'a', 10); // end of s s[10] = 0; printf("s=%s,length=%d\n",s,strlen(s)); // reallocate size of s s = (char*)realloc(s,21); memset(s + 10, 'b', 10); s[20] = 0; printf("s=%s,length=%d\n",s,strlen(s)); free(s);}
執行結果 s = aaaaaaaaaa , length = 10 s = aaaaaaaaaabbbbbbbbbb , length = 20
Reference日向俊二,C/C++辭典,博碩文化,2002