C語言自定義字符串複製函數

用C語簡單實現一個字符串複製函數

 

/*
 ============================================================================
 Name        : Cdemo.c
 Author      : Avery
 Version     :
 Copyright   : Your copyright notice
 Description : str_cpy in C, Ansi-style
 ============================================================================
 */

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

/**
 * char *str_cpy(char *source, char *dist)
 */
char *str_cpy(char *source, char *dist) {
	if (source == NULL && dist == NULL) {
		return NULL;
	}
	int char_count = 0;
	char *source_tem = source; //save the first address
	while (*source != '\0') { //get source string length
		char_count++;
		source++;
	}
	dist = (char *) malloc(sizeof(char) * char_count); //init dist
	char *dist_tem = dist;
	while ((*dist++ = *source_tem++) != '\0'); // copy
	*dist = '\0';
	return dist_tem;
}

//Test
int main(void) {
	char *source = "Avery Zhong *************";
	char *dist = "";
	char *result = str_cpy(source, dist);
	printf("%s", result);
        free(result);
	return EXIT_SUCCESS;
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章