这个看似简单的问题,往往容易出错。我初次编写时,编译一次性通过,但运行时总是发生异常。主要问题在与:1、没有给目标串指针变量分配内存。2、为了简练把地址递增写成strSource++的形式。结果输出的是空串,原因在于输出时,指针此时正好指向了字符串的末尾。一下程序在VC6.0下调试通过,可供参考。注释的地方为需要注意的地方
/************************************************************************/
/* author:jychen                                                                                                                */
/* function 字符串拷贝函数                                                                                                */
/*Version:0.0.1                                                                                                                 */
/************************************************************************/
#include "stdio.h"
#include "string.h"
#include "malloc.h"
void main()
{
     void StringCopy(const char *strSource, char *strDestination);
     char *strSource={"hello world !"};
     char *strDestination;
     //给strDestination·分配内存空间,否则运行时会有异常发生
     strDestination = (char *) malloc (strlen(strSource) + 1);
     if (strDestination == NULL)
     {
             printf("内存分配失败\n");
             return ;
     }
     StringCopy(strSource, strDestination);
     printf("%s\n",strDestination);
     free(strDestination);
}
void StringCopy(const char *strSource, char *strDestination)
{
     int i=0; //地址计数器
     while(*(strSource+i)!='\0')
     {
         //不能写成 strDestination++的形式,因为strDestination是字符串的首地址
         *(strDestination+i)=*(strSource+i);
         i++;
     }    
    *(strDestination+i)='\0';//给拷贝后的字符串加上结束符
}