我正在读一本关于 c 的书,下面的段落对我来说有点不清楚:
Surprisingly, passing the pointer is not efficient in the above example! That's because of the fact that the int type is 4 bytes and copying it is more efficient than copying 8 bytes of its pointer. But this is not the case regarding structures and arrays. Since copying structures and arrays is done byte-wise, and all of the bytes in them should be copied one by one, it is usually better to pass pointers instead.
据我所知,CPU 中的所有操作都仅限于算术(加号或 minùس)或按位操作,所以
作者说的拷贝数组和结构体是什么意思,int拷贝不就是移位操作吗?
其次:是指针数组吗?
注意:书名为Extreme C,由packT出版 以下示例是作者所指的:
#include <stdio.h>
void func(int* a) {
int b = 9;
*a = 5; a = &b;
}
int main(int argc, char** argv) {
int x = 3;
int* xptr = &x;
printf("Value before call: %d\n", x);
printf("Pointer before function call: %p\n", (void*)xptr); func(xptr);
printf("Value after call: %d\n", x);
printf("Pointer after function call: %p\n", (void*)xptr);
return 0;
}
'''
最佳答案
书上说的不清楚,也是错误的。
假设似乎是 8 字节指针比 4 字节整数“更难”复制。这对几乎所有现代 CPU 都是错误的。
此外,关于复制数组的部分完全是错误的。这不是 C 所做的。在 C 中传递数组不涉及复制。这实际上就像传递一个指针。
然而,关于结构的部分是正确的...只要该结构不仅仅是一个简单的整数或字符,而是“更大的东西”。
What does the writer mean about copying array
听起来像垃圾...因为 C 不会通过复制来传递数组
What does the writer mean about copying ... structure,
结构是按值复制的。因此,将结构传递给函数涉及复制结构的每个字节。如果结构很大,那将是相当昂贵的。
are pointers array?
没有。指针就是指针。但是......在正确的情况下,指针可以用作数组,因为 *(p + i)
与 p[i]
关于c++ - 在 c 中复制数组与复制 int 成本和性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68581674/