【发布时间】:2018-06-03 09:59:28
【问题描述】:
我正在使用调试器来阅读这段代码,我对while ((*d++ = *s2++)); 有点困惑 - 在调试器变量中,d 似乎在每次循环后都会缩短(从 'Hello hello' 变为 'ello hello' 而s1 更改为 'cello hello')。循环通过的while循环是什么(不应该是while(condition); do(something))吗?
为什么d和s1的变量值不一样(不是d是指向s1的指针)?而当他们返回主函数时,是curdst=dst的指针吗?
/*
Input: char pointers for source (s2) and destination (s1)
Output: returns the pointer to the destination (s1)
*/
char *my_strcpy(char * , const char * );
int main()
{
char src[] = "cs23!";
char dst[]="Hello hello";
char *curdst;
int len=0;
while(src[len++]);
// do the copy
curdst= my_strcpy(dst, src);
// check to see if the NULL char is copied too.
printf("dst array %s and last element %d\n", dst, atoi(&dst[len]));
return 0;
}
char *my_strcpy(char *s1, const char *s2) {
register char *d = s1;
// print the pointer variables address and their contents, and first char
printf("s2 address %p, its contents is a pointer %p to first char %c \n", (void *)&s2, (void *)s2, *s2);
printf("s1 address %p, its contents is a pointer %p to first char %c \n", (void *)&s1, (void *)s1, *s1);
while ((*d++ = *s2++));
return(s1);
}
【问题讨论】:
-
请注意,
*d++ = *s2++与*d++ == *s2++非常不同。在这里,您将使用来自*s2的值覆盖*d中的值,直到到达s2中的空终止符。 -
这里的条件是
*s2不是零(字符串空终止符)。 -
查看this answer 了解类似情况的详细信息。