c++ - 在 c 中复制数组与复制 int 成本和性能

标签 c++ arrays c function data-structures

我正在读一本关于 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/

相关文章:

c++ - LLVM IR : Identifying Variables with Metadata Nodes

arrays - 在数组中的给定位置之后查找元素第一次出现的有效方法是什么?

c - .bmp 图像比较显示 image.bmp 上的 EOF

c++ - 为什么在 Ubuntu 18.04.1 的 netinet 中没有定义 in_addr6?

c++ - QTreeview 增加 View 大小

c++ - SelectObject 使用在构造函数中创建的 hbitmap 返回 NULL

c++ - 如何在 C++ 中重载 "operator %"

arrays - 有没有更优雅的方式来做到这一点?

java - 什么 Java 库可以将 PostgreSQL 数组文字映射到 Java 数组或列表?

c - 单元测试 C 模块静态变量