指针实现字符串插入

本文探讨了指针在字符串操作中的应用,包括如何利用指针实现字符串插入,通过memset清除内存以避免乱码问题,以及将数组地址赋给指针理解地址变化。示例中强调了在使用strcpy时,配合memset清除内存的重要性。

指针的指示作用


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void insert(char *x, char *y, int i){
	
	//char *temp = NULL;
	//printf("拼接前的x字符串长度是%d\n", strlen(x));
	//printf("拼接前的y字符串长度是%d\n", strlen(y));
	char *temp = malloc(10*sizeof(char)); 
	//strncat(temp, x, 2);
	//char string3[100];
	//char *temp = string3;
	memset(temp, '\0', sizeof(temp));//该函数用来清除内存位置 
	strncpy(temp, x, i);
	/*for(int j = 0; j < strlen(temp); j++){
		printf("%s", *(temp + i));
	}*/
	//printf("%s", temp);
	//printf("拼接后的temp字符串长度是%d\n", strlen(temp));
	//printf("拼接后的x字符串长度是%d\n", strlen(x));
	strcat(temp, y);
	//printf("拼接后的y字符串长度是%d\n", strlen(y));
    strcat(temp, x + i);
	//for(int j = 0; j < strlen(temp); j++){
	//	printf("%c", *(temp + j));
    //}
	//printf("%s", temp);
	puts(temp); 
	free(temp);
	puts(temp); 
}

int main(){
	char string1[]={'a','b','c','d','e'};
	char string2[]={'f','g','h'};
/*	char string1[5];
	strcpy(string1, "abcde");
	char string2[3];
	strcpy(string2, "fgh");*/
	//char string1[]={"abcde"};
	//char string2[]={"fgh"};
	char *x = string1;
	char *y = string2;
	//char *result = &insert(string1, string2, 2);
	insert(x, y, 1);
	return 0;
}

依靠temp + i来移动指针来达到从数组中任意取值的效果。

memset清除内存(配合strcpy使用)

如果缺少了清除内存位置这个语句的话,temp中会存在乱码,那是没有清空的内存。在c语言文档中strcpy的用法示例中,就使用了这一语句。非常重要

memset(temp, '\0', sizeof(temp));//该函数用来清除内存位置

数组地址赋给指针,指针中存放的地址变化

	char *temp = NULL;
	printf("%8u\n", temp);
	//printf("拼接前的x字符串长度是%d\n", strlen(x));
	//printf("拼接前的y字符串长度是%d\n", strlen(y));
	//char *temp = malloc(10*sizeof(char)); 
	//strncat(temp, x, 2);
	char string3[100];
	printf("%8u\n", &string3);
	temp = string3;
	printf("%8u\n", temp);
	//char *temp = string3;
	memset(temp, '\0', sizeof(temp));//该函数用来清除内存位置 
	strncpy(temp, x, i);
	/*for(int j = 0; j < strlen(temp); j++){
		printf("%s", *(temp + i));
	}*/
	//printf("%s", temp);
	//printf("拼接后的temp字符串长度是%d\n", strlen(temp));
	//printf("拼接后的x字符串长度是%d\n", strlen(x));
	strcat(temp, y);
	//printf("拼接后的y字符串长度是%d\n", strlen(y));
    strcat(temp, x + i);
	//for(int j = 0; j < strlen(temp); j++){
	//	printf("%c", *(temp + j));
    //}
	//printf("%s", temp);
	printf("%8u\n", temp);
	puts(temp); 
	

空指针里存放的地址就是0,string数组的头地址赋给了指针temp,那么temp里存放的就是数组的地址。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值