串的堆分配存储结构

以动态数组为例子

该程序可实现将两个串("data.bian" 和 "cheng.net")合并为一个串

代码如下:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main(){
	char *a=NULL;				//定义个空指针 
	char *b=NULL;
	a=(char*)malloc(10*sizeof(char));		//分配动态内存  10个char 
	b=(char*)malloc(10*sizeof(char));
	strcpy(a,"data.bian");		//注意,程序中给 a 和 b 赋值时,使用了 strcpy 复制函数。这里不能直接用 a ="data.biancheng",程序编译会出错
	strcpy(b,"cheng.net");		//要是直接赋值的话,动态申请的存储空间虽然申请了,结果还没用呢就丢了。
	int strlenga=strlen(a);		//计算字符串长度 
	int strlengb=strlen(b);
	if(strlenga<strlenga+strlengb)
	{
		a=(char*)realloc(a,(strlenga+strlengb+1)*sizeof(char));		//如果a的长度放不下a+b重新分配动态内存 
	}
	int i;
	for(i=strlenga;i<strlenga+strlengb;i++)			//i=9开始算  i<18  i++ 
	{
		a[i]=b[i-strlengb];				//i[9]=b[0]  i[10]=b[1]
	}
	a[strlenga+strlengb]="\0";			//结尾标记 
	printf("%s\n",a);					//打印组合后的字符串 
	free(a);							//释放动态数组 
	free(b);
	return 0;
}

编译结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wiyoo0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值