指针实现字符串插入

醉酒当歌 提交于 2020-01-30 02:11:14

指针的指示作用


#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里存放的就是数组的地址。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!