博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(原創) 如何重新動態配置記憶體空間? (C/C++) (C)
阅读量:7089 次
发布时间:2019-06-28

本文共 865 字,大约阅读时间需要 2 分钟。

Problem

C++里我NEW了一個CHAR[10]  後來發現不購大  想加大空間 而不損害原來的內容怎麽辦?
Solution
使用realloc()重新配置記憶體大小,類似VB的redim()。
header : stdlib.h
signature : void* realloc(void* pmem, size_t size);
pmem : 一個pointer,指向已經配置出去的記憶體區塊
size : 新的記憶體空間大小(byte)
Sample Code

ContractedBlock.gif
ExpandedBlockStart.gif
ExpandedBlockStart.gifContractedBlock.gif/**//* 
InBlock.gif(C) OOMusou 2007 
http://oomusou.cnblogs.com
InBlock.gif
InBlock.gifFilename    : realloc.cpp
InBlock.gifCompiler    : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
InBlock.gifDescription : Demo how to reallocate char
InBlock.gifRelease     : 05/26/2007 1.0
ExpandedBlockEnd.gif
*/
None.gif#include 
"stdio.h"
None.gif#include 
"stdlib.h"
None.gif#include 
"string.h"
None.gif
ExpandedBlockStart.gifContractedBlock.gif
int main() dot.gif{
InBlock.gif  
char* s = (char*)malloc(11);
InBlock.gif  memset(s, 
'a'10);
InBlock.gif  
// end of s
InBlock.gif
  s[10= 0;
InBlock.gif  printf(
"s=%s,length=%d\n",s,strlen(s));
InBlock.gif  
InBlock.gif  
// reallocate size of s
InBlock.gif
  s = (char*)realloc(s,21);
InBlock.gif  memset(s 
+ 10'b'10);
InBlock.gif  s[
20= 0;
InBlock.gif  printf(
"s=%s,length=%d\n",s,strlen(s));
InBlock.gif  
InBlock.gif  free(s);
ExpandedBlockEnd.gif}

執行結果

None.gif
s
=
aaaaaaaaaa
,
length
=
10
None.gifs
=
aaaaaaaaaabbbbbbbbbb
,
length
=
20

Reference
日向俊二,C/C++辭典,博碩文化,2002

转载地址:http://oyfql.baihongyu.com/

你可能感兴趣的文章
数据结构 哥尼斯堡的“七桥问题” (并查集)
查看>>
Public Prize
查看>>
如何在本地同时管理github仓库和codingnet仓库?
查看>>
014:Django内置的URL转换器
查看>>
jQuery smartMenu右键自定义上下文菜单插件
查看>>
Java基础 - 面向对象 - 构造方法
查看>>
手动爬虫之报头及代理封装类(python3)
查看>>
图的最大匹配算法
查看>>
算法: 整数中1出现的次数(从1到n整数中1出现的次数)
查看>>
如何理解JavaScript中的原型和原型链
查看>>
Container With Most Water
查看>>
Qt 给控件QLineEdit添加clicked事件方法
查看>>
.iOS APP Project or Mac APP Project编译错误提示: My Mac 64-bit is not valid for Running the scheme...
查看>>
杂七杂八集合
查看>>
美学心得(第一百九十九集) 罗国正
查看>>
Cocos2d-x之绘制矩形
查看>>
上传图片
查看>>
分块矩阵和行列式
查看>>
陶哲轩实分析引理8.4.5
查看>>
WINCE 下载地址(转)
查看>>