我有一个代码块:
int main ()
{
char *p1 = "Hello";
char *p2;
p2 = (char*)malloc (20);
memset (p2, 0, 20);
while (*p2++ = *p1++);
printf ("%s\n", p2);
}
Run Code Online (Sandbox Code Playgroud)
但我无法解释线的工作(*p2 ++ =*p1 ++); 你能让我知道这个公式中的操作顺序吗?
Meh*_*dad 18
它是经典的C代码,通过将所有内容放在一行中来试图看起来非常聪明.
while (*p2++ = *p1++); 相当于
strcpy(p2, p1);
p1 += strlen(p1) + 1;
p2 += strlen(p2) + 1;
Run Code Online (Sandbox Code Playgroud)
换句话说,它复制以空字符结尾的字符串,p1最后指向源字符串p2的末尾并指向目标字符串的结尾.
这是一个字符串副本,但您丢失了原始指针值.您应该保存原始指针值.
int main ()
{
char *p1 = "Hello";
char *p2 = malloc(20);
char *p3 = p2;
memset (p2, 0, 20);
while (*p2++ = *p1++);
printf ("%s\n", p3);
}
Run Code Online (Sandbox Code Playgroud)
while循环的实际语义解释如下:
for (;;) {
char *q2 = p2; // original p2 in q2
char *q1 = p1; // original p1 in q1
char c = *q1; // original *p1 in c
p2 += 1; // complete post increment of p2
p1 += 1; // complete post increment of p1
*q2 = c; // copy character *q1 into *q2
if (c) continue; // continue if c is not 0
break; // otherwise loop ends
}
Run Code Online (Sandbox Code Playgroud)
的顺序q1和q2被保存,并且为了使p2与p1递增可以互换.另存*q1到c可发生后的任何时间q1被保存.的分配c到*q2可发生后的任何时间c被保存.在我的信封背面,这至少有40种不同的解释.
| 归档时间: |
|
| 查看次数: |
2079 次 |
| 最近记录: |