博客
关于我
强烈建议你试试无所不能的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/

你可能感兴趣的文章
grep 技巧
查看>>
4月第一周中国五大顶级域名增3.7万 美国减3457个
查看>>
RedHat6使用Centos6的yum源
查看>>
NoSQL最新现状和趋势:云NoSQL数据库将成重要增长引擎
查看>>
206. Reverse Linked List - LeetCode
查看>>
Linux环境下Maven仓库的搭建(nexus)及Mavan的简单使用
查看>>
批量替换多个文件中的字符
查看>>
我的友情链接
查看>>
IndexWriter和IndexReader对象分析
查看>>
Linux设置网络及问题排查
查看>>
linux array数组
查看>>
最简单的网页换肤(jQuery)
查看>>
Python3 通过 pika 连接 RabbitMQ 的基本用法
查看>>
我的友情链接
查看>>
The operation couldn’t be completed. Unable to log in with account ''
查看>>
ESXi为虚拟机选择网络适配器 (2093486)
查看>>
C/C++踩坑记录(二)一段有趣的常量字符串
查看>>
MongoDB主从集群
查看>>
关于Linux的字符测试的详解
查看>>
htop使用详解
查看>>