我正在看戴上举老师的书《删繁就简-单片机入门到精通》第四章,第230也有个例子:
改写的strcpy:
先不考虑程序里变量有些不一样。
我在dev c++里写了一个完整调用的程序
#include <stdio.h>
#include <string.h>
#define UINT32 unsigned long int
#define UINT8 unsigned char
#define ERR_PARAMETER 1
#define ERR_EMPTY_STR 2
UINT32 strcpy1(UINT8 *desBuf,UINT8 *srcBuf)
{
UINT32 count;
count=0;
if((UINT32)desBuf==(UINT32)srcBuf)
{
return ERR_PARAMETER;
}
if(*srcBuf==0x00)
{
return ERR_EMPTY_STR;
}
while((*desBuf++=*srcBuf++)!=0x00)
//while((*desBuf++=*srcBuf++)!='\0')
{
count++;
}
return count;
}
int main(void)
{
UINT32 i;
UINT8 SrcBuf[8]={1,2,3,4,5,6,7,8};
UINT8 DesBuf[8]={0,0,0,0,0,0,0,0};
i=strcpy1(DesBuf,SrcBuf);
printf("copy num = %ld\n",i);
for(i=0;i<sizeof(DesBuf);i++)
printf("DesBuf[%ld]=%d\n",i,DesBuf[i]);
return 0;
}
运行结果
也就是说拷贝了9个数。
我用VC写了另一个程序
#include "stdafx.h"
#define UINT32 unsigned long int
#define UINT8 unsigned char
#define ERR_PARAMETER 1
#define ERR_EMPTY_STR 2
UINT32 strcpy(UINT8 *desBuf,UINT8 *srcBuf)
{
UINT32 count;
count=0;
if((UINT32)desBuf==(UINT32)srcBuf)
{
return ERR_PARAMETER;
}
if(*srcBuf==0x00)
{
return ERR_EMPTY_STR;
}
while((*desBuf++=*srcBuf++)!=0x00)
//while((*desBuf++=*srcBuf++)!='\0')
{
count++;
}
return count;
}
int main(void)
{
UINT32 i;
UINT8 SrcBuf[8]={1,2,3,4,5,6,7,8};
UINT8 DesBuf[8]={0,0,0,0,0,0,0,0};
i=strcpy(DesBuf,SrcBuf);
printf("copy num = %ld\n",i);
for(i=0;i<sizeof(DesBuf);i++)
printf("DesBuf[%ld]=%d\n",i,DesBuf[i]);
return 0;
}
运行结果:
竟然变成15个。
我还不死心,书第228页有个“标准答案”
我用devc++写了个调用程序
#include <stdio.h>
//#include <string.h>
#define UINT32 unsigned long int
#define UINT8 unsigned char
char * strcpy(char * strDest,const char * strSrc)
{
if((strDest==NULL)||(strSrc==NULL))
{
return NULL;
}
char *strDestCopy=strDest;
while((*strDest++=*strSrc++)!='\0');
return strDestCopy;
}
int main(void)
{
char i;
char *p;
UINT8 SrcBuf[8]={1,2,3,4,5,6,7,8};
UINT8 DesBuf[8]={0,0,0,0,0,0,0,0};
p=strcpy(DesBuf,SrcBuf);
printf("copy num = %d\n",*p);
for(i=0;i<*p;i++)
printf("DesBuf[%ld]=%d\n",i,DesBuf[i]);
return 0;
}
运行结果:
成了一个。
然后我用VC又写了一个调用程序
#include "stdafx.h"
#define UINT32 unsigned long int
#define UINT8 unsigned char
char * strcpy(char * strDest,const char * strSrc)
{
if((strDest==NULL)||(strSrc==NULL))
{
return NULL;
}
char *strDestCopy=strDest;
while((*strDest++=*strSrc++)!='\0');
return strDestCopy;
}
int main(void)
{
char i;
char *p,*p1,*p2;
char SrcBuf[8]={1,2,3,4,5,6,7,8};
char DesBuf[8]={0,0,0,0,0,0,0,0};
p1=SrcBuf;
p2=DesBuf;
p=strcpy(p2,p1);
printf("copy num = %d\n",*p);
for(i=0;i<*p;i++)
printf("DesBuf[%ld]=%d\n",i,DesBuf[i]);
return 0;
}
运行结果
请问高手,我哪里错了?谢谢!
|