c - 将指针数组复制到另一个指针的有效方法

标签 c

如何将指针数组复制到另一个指针。

我的方法是这样的

int *ptr2[(i-1)*100];
int *ptr1;

ptr1=&ptr2[(i-1)*100];

有效的复制方法是什么,可以减少 CPU 周期。

最佳答案

如果需要复制(复制)ptr2,则需要使用正确的类型声明ptr1,并为ptr1数组分配空间,然后将 ptr2 的内容复制到 ptr1

#include <malloc.h>
#include <string.h>

int *ptr2[(i-1)*100];
int **ptr1; // a pointer to a pointer to an int

ptr1 = malloc(sizeof(ptr2));
memcpy(ptr1, ptr2, sizeof(ptr2));

注意:这是一个示例。始终确保 malloc 在使用内存块之前已分配该内存块,并在不再需要时将其释放(使用 free)

另一方面,如果您只想创建 ptr2 的别名

int *ptr2[(i-1)*100];
int **ptr1; // a pointer to a pointer to an int

ptr1 = ptr2;

关于c - 将指针数组复制到另一个指针的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31803511/

相关文章:

c - 为什么输出是0.000000?

C 中的 Char * 指针与整数

C从结构中访问结构指针变量元素

c - X11/Xlib : virtual keyboard input and keyboard mapping synchronization issue

将十六进制转换为 Ascii 内存访问

C - 替代#ifdef

c - pthread线程池场景

c - 密码恢复程序

c - 在 C i/o 中跳过代码行

C语言多处理execvp()