1. 程式人生 > >c理解提高(5)字串copy函式技術推演

c理解提高(5)字串copy函式技術推演

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

void main01()
{
	//通過棧的方式對資料進行拷貝
	char a[] = "i am a student";
	char b[64];
	int  i = 0;

	for (i=0; *(a+i) != '\0'; i++)
	{
		*(b+i) = *(a+i);
	}

	//0沒有copy到b的buf中.

	b[i] = '\0'; //重要
	printf("a:%s \n", a);
	printf("b:%s \n", b);

	system("pause");
	return ;
}

//字串copy函式技術推演
//copy函式的第一種形式
//form形參 形參to 的值 不停的在變化....
//不斷的修改了from和to的指向
void copy_str01(char *from, char *to)
{
	for (; *from!='\0'; from++, to++)
	{
		 *to = *from;
	}
	*to = '\0';

	return ;
}


//copy函式的第二種形式
//*操作 和++的操作  ++ 優先順序高 
void copy_str02(char *from, char *to)
{
	for (; *from!='\0';)
	{
		*to++ = *from++;  //  先 *to = *from;  再from++, to++ 
	}
	*to = '\0'; //

	return ;
}

//copy函式的第三種形式
//不需要最後新增0
void copy_str03(char *from, char *to)
{
	while( (*to = *from) != '\0' )
	{
		from ++; 
		to ++;
	}
}

//copy函式的第四種形式
//直接在判斷條件中進行操作
void copy_str04(char *from , char *to)
{
	while ( (*to++ = *from++) != '\0')
	{
		;
	}
}

//copy函式的第五種形式
//在判斷條件中直接得到結果,不需要得到比較的結果
void copy_str05(char *from , char *to)
{
	//*(0) = 'a';
	while ( (*to++ = *from++) )
	{
		;
	}
}

//直接改變傳入的實參的值是不恰當的做法
void copy_str25_err(char *from , char *to)
{
	//*(0) = 'a';
	while ( (*to++ = *from++) )
	{
		;
	}

	printf("from:%s \n", from);
	
}


//不要輕易改變形參的值, 要引入一個輔助的指標變數. 把形參給接過來.....
int copy_str26_good(char *from , char *to)
{
	//*(0) = 'a';
	char *tmpfrom = from;
	char *tmpto = to;
	if ( from == NULL || to == NULL)
	{
		return -1;
	}


	while ( *tmpto++ = *tmpfrom++ ) ;  //空語句

	printf("from:%s \n", from);
		
}

int main02()
{
	int ret = 0;
	char *from = "abcd";
	char buf2[100]; 
	//copy_str21(from, buf2);
	//copy_str22(from,buf2);
	//copy_str23(from, buf2);
	//copy_str24(from, buf2);
	//copy_str25(from ,buf2);
	//printf("buf2:%s \n", buf2);

	{
		//錯誤案例
		char *myto = NULL;  //要分配記憶體
		//copy_str25(from,myto );
	}
	{
		char *myto = NULL;  //要分配記憶體
		
		ret = copy_str26_good(from, myto);
		if (ret != 0)
		{
			printf("func copy_str26_good() err:%d  ", ret);
			return ret;
		}
	}
	system("pause");
	return ret;
}


int main03()
{
	int ret = 0;
	char *from = "abcd";
	char buf2[100]; 

	printf("copy_str25_err begin\n");
	copy_str25_err(from, buf2);
	copy_str26_good(from, buf2);
	printf("copy_str25_err end\n");
	return 0;
}