指针&&strcpy的实现问题
void strcpy(char *strDest, const char *strSrc)
{
assert( (strDest != NULL) && (strSrc != NULL) );
while( (*strDest++ = * strSrc++) != ‘\0’ );
}
代码如上
我的问题是:
1. while( (*strDest++ = * strSrc++) != ‘\0’ ); 这个语句的执行过程? 什么时候执行 ='\0'?
2.这属于c语言的那一章节的问题?
[解决办法]
1. *strDest=*strSrc;
2.strSrc++;
3.strDest++;
(*strDest++ = * strSrc++) 这句返回(*strSrc)的值,字符串最后一个字符是'\0'.
字符串的知识
[解决办法]
过程就是把源字符串的字符一个个赋给目标字符串。。当*strSrc == '\0'也就是源字符串结束的时候while结束。
可以看一下C语言教材里讲字符串那一节的内容,知道C字符串是以'\0'结束的。
[解决办法]
(*strDest++ = * strSrc++) != '\0';
0098139C mov eax,dword ptr [strDest] ;eax= strdest
0098139F mov ecx,dword ptr [strSrc] ;ecx = strsrc
009813A2 mov dl,byte ptr [ecx] ;dl = *strsrc
009813A4 mov byte ptr [eax],dl ;*strdest = dl
009813A6 mov eax,dword ptr [strDest] ;eax = strdest
009813A9 add eax,1 ;eax++
009813AC mov dword ptr [strDest],eax ;strDest = eax
009813AF mov ecx,dword ptr [strSrc] ;ecx = strSrc
009813B2 add ecx,1 ;ecx++
009813B5 mov dword ptr [strSrc],ecx ;strSrc = ecx
vs2008下编译,反汇编了下,证实了如一楼所说
[解决办法]
while( (*strDest++ = * strSrc++) !='\0');
0028333F 8B 45 08 mov eax,dword ptr [strDest]
00283342 8B 4D 0C mov ecx,dword ptr [strSrc]
00283345 8A 11 mov dl,byte ptr [ecx]
00283347 88 10 mov byte ptr [eax],dl
00283349 8B 45 08 mov eax,dword ptr [strDest]
0028334C 0F BE 08 movsx ecx,byte ptr [eax]
0028334F 8B 55 08 mov edx,dword ptr [strDest]
00283352 83 C2 01 add edx,1
00283355 89 55 08 mov dword ptr [strDest],edx
00283358 8B 45 0C mov eax,dword ptr [strSrc]
0028335B 83 C0 01 add eax,1
0028335E 89 45 0C mov dword ptr [strSrc],eax
00283361 85 C9 test ecx,ecx
00283363 74 0C je strcpy2+81h (283371h)
00283365 C7 85 3C FF FF FF 01 00 00 00 mov dword ptr [ebp-0C4h],1
0028336F EB 0A jmp strcpy2+8Bh (28337Bh)
00283371 C7 85 3C FF FF FF 00 00 00 00 mov dword ptr [ebp-0C4h],0
0028337B 83 BD 3C FF FF FF 00 cmp dword ptr [ebp-0C4h],0
00283382 74 02 je strcpy2+96h (283386h)
00283384 EB B9 jmp strcpy2+4Fh (28333Fh)
纠正1楼的一个问题, 是把strDest 的值和 '\0' 字符串结束符做比较,然后判断结果