字符串做函数参数

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

void copy_str21(char *from, char *to)
{
    for(; *from != '\0'; from++, to++)
    {

        *to = *from;
    }
    *to = '\0';
}

//* 操作和 ++操作 
 //++优先级高
void copy_str22(char *from, char *to)
{
    for(; *from != '\0'; )
    {

        *to++ = *from++;   //先执行to++ from++ 再执行 *to++ = *from++
    }
    *to = '\0';
}

void copy_str23(char *from, char *to)
{
    while((*to = *from) != '\0')
    {
        from++;
        to++;
    }
}

void copy_str24(char *from, char *to)
{
    while((*to++ = *from++) != '\0')
    {
        ;
    }
}

void copy_str25(char *from, char *to)
{
    while((*to++ = *from++))
    {
        ;
    }
}

int main()
{
    char *from = "abcde";
    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);

    return 0;
} 

字符串拷贝的不同实现

字符串后的   ’\0‘

内存分配图

定义指针 一定要分配内存, 没有内存就没有指针

int copy_str26_good(char *from, char *to)

{

  if(from == NULL || to == NULL)

  {

    return -1;

  } 

  while ( *to++ = *from++) ; //空语句

}

执行语句之前先判断是否满足要求,如果满足再执行 while ( *to++ = *from++) ; 拷贝

 

以下代码对吗?

void copy_str25(char *from, char *to)
{
    while((*to++ = *from++))
    {
        ;
    }
printf("from:%s \n", from); }
指针的指向已经改变,已经调到‘\0’后面,故printf后面没有任何数据。


正确的代码应该重新定义辅助指针变量 把形参给接过来 不要轻易改变形参

 void copy_str25(char *from, char *to)

{
  char *tmpfrom = from;
  char *tmpto = to;

  if(from == NULL || to == NULL)

  {

    return -1;

  } 

  while ( *to++ = *from++) ; //空语句


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

 

posted @ 2017-04-10 17:09  Liu_Jing  Views(887)  Comments(0)    收藏  举报