C:理解此代码while循环中的指针有困难
我正在使用一个调试器来通读这段代码,我对C:理解此代码while循环中的指针有困难,c,pointers,C,Pointers,我正在使用一个调试器来通读这段代码,我对while((*d++=*s2++)有点困惑-在调试器变量中,d在每次循环后似乎都会缩短(从'Hello Hello'变为'ello Hello',而s1变为'cello Hello')。while循环通过什么(不应该是while(条件);do(某事)) 为什么d和s1的变量值不相同(d不是指向s1的指针)?当它们返回到主功能时,curdst=是否为dst的指针 /* Input: char pointers for source (s2) a
while((*d++=*s2++)有点困惑代码>-在调试器变量中,d在每次循环后似乎都会缩短(从'Hello Hello'
变为'ello Hello'
,而s1
变为'cello Hello'
)。while循环通过什么(不应该是while(条件);do(某事))
为什么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);
}
这是一个非常典型的strcpy()
教学实现。它的工作原理如下:
my_strcpy()
接受两个参数。第一个参数是指向目标字符数组的第一个元素的指针。第二个参数是指向源字符串的第一个元素的指针,即以NUL
(又称\0
)字符结尾的字符数组。函数将字符从源字符串复制到目标缓冲区,包括NUL
终止符,并返回指向目标缓冲区第一个元素的指针
char *my_strcpy(char *s1, const char *s2) {
- 首先,复制第一个参数,因为我们需要在复制完成后返回它
char *d = s1;
- 然后,复制字符;这是在一个紧密的循环中完成的,工作方式如下:
- 将当前字符
*s2
复制到d
指向的位置,就像执行*d=*s2
一样;然后
- 增量
d
指向目标缓冲区中的下一个位置,就像执行d++
一样;增量s2
指向要复制的下一个字符,就像执行s2++
一样;及
- 如果复制的最后一个字符是
NUL
,则退出循环
这是用非常简洁的方式写的:
while (* d++ = * s2++);
*s2++
表示“取s2
指向的字符,然后递增s2
”。类似地,*d++
作为左侧值表示“使用d
指向的变量,然后递增d
”。运算符的优先级顺序有助于省去括号,因为++
的优先级高于*
,后者的优先级高于=
。赋值的值就是赋值,因此循环在赋值字符的值为0时结束
- 最后,返回函数未更改的
s1
return s1;
}
请注意,*d++=*s2++
与*d++=*s2++
非常不同。在这里,您将使用*s2
中的值覆盖*d
中的值,直到到达s2
中的空终止符。这里的条件是*s2
不是零(字符串空终止符)。请参阅类似内容的详细信息。谢谢!!正在更改*d
更改s1
以便在返回s1
时,您已将s2复制到s1?@helloworld:您已将s2
指向的字符串复制到s1
指向的缓冲区中。