[英]what does the following code do in C?
I saw the following code from somewhere: 我从某处看到了以下代码:
while(*i++ = *j++)
{
}
but what is this code doing? 但是这段代码在做什么? what is the meaning of it?
它是什么意思?
It copies elements from an array (or a pointer to an array) called j
to one called i
. 它将元素从名为
j
的数组(或指向数组的指针)复制到名为i
元素。 It does this until it finds a value (from j
) which is equivalent to zero. 这样做直到找到一个等于零的值(来自
j
)。
This is a common idiom for copying C-style, null-terminated strings; 这是复制C样式,以null终止的字符串的常见用法。 it could also be used to copy an array of integers terminated by a sentinel zero.
它也可以用来复制以前哨零结尾的整数数组。
In case the size of j
can be known in advance, it might be better to use memcpy()
. 如果可以预先知道
j
的大小,则最好使用memcpy()
。 And in case the size of j
cannot be known in advance, it is likely the code is unsafe, because the proper size to allocate for i
cannot be known either. 并且如果无法事先知道
j
的大小,则代码很可能是不安全的,因为也无法知道为i
分配的适当大小。
Most likely, if i and j are char*, then it copyes null-terminated string j into memory that starts at i. 最有可能的是,如果i和j为char *,则它将以空终止的字符串j复制到以i开头的内存中。 You might wanna keep in mind that i and j itself changes (
i += strlen(j)
) so code above also breaks the pointers to a strings. 您可能要记住,i和j本身会发生变化(
i += strlen(j)
),因此上面的代码还会中断指向字符串的指针。
It copies the data pointed to by j, to the array pointed to by i, and continues until a value of 0 has been copied. 它将j指向的数据复制到i指向的数组,并继续直到复制了0值。 It is perhaps used to copy a null-terminated string.
它可能用于复制以空值结尾的字符串。 To be even more clever, you can use
为了更加聪明,您可以使用
while(*i++ = *j++);
*j++ derefrences the pointer, increments its value. * j ++取消刷新指针,增加其值。
*i++ = *j++ assigns the old value of *j to *i, then *i++ increments this value and saves it for use the next time * i ++ = * j ++将* j的旧值分配给* i,然后* i ++将该值递增并保存以供下次使用
while(*i++ = *j++)
is executed. 被执行。
If i and j are char[], then 如果i和j是char [],则
while(*i++ = *j++)
is copying characters from j[] to i[] until NULL character is reached. 将字符从j []复制到i [],直到到达NULL字符。
In addition to the other answers, while(*i++ = *j++){}
is a less readable, more compact and more dangerous way of writing 除了其他答案,
while(*i++ = *j++){}
是一种不太易读,更紧凑和更危险的书写方式
*i = *j;
while(*i != 0)
{
i++;
j++;
*i = *j;
}
The two cases will generate exactly the same machine code . 这两种情况将生成完全相同的机器代码 。
It primarily depends on what i
and j
are. 这主要取决于
i
和j
是什么。 One case can as be follows. 一种情况如下。
Assume that i
and j
are two pointers to a character string, then the value of i
and j
will get simultaneously increased, and assign the value of *j
as *i
, whenever the value of j
becomes 0
ie, \\0
the loop will exit after assigning that 0
to *i. 假设
i
和j
是指向字符串的两个指针,则i
和j
的值将同时增加,并将*j
的值分配为*i
,每当j
的值变为0
即\\0
,循环将将0
分配给* i后退出。
Obviously this can be used to copy the content of j
to i
. 显然,这可以用于将
j
的内容复制到i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.