c - 如何在C中将数组A的指针设置为指向数组B

标签 c arrays pointers

我试图通过从数组 B 指向数组 A 来交换 C 中的两个数组,然后释放 A,这样我只剩下数组 B 和数组 A 的内容。这可能吗?

代码:

int *a = malloc(4*sizeof(int));
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
int *b = malloc(4*sizeof(int));
//Assign pointer from b to memory position of a so b[] = a[]?

提前谢谢你,

沃特

最佳答案

#include <string.h>

#define ARRAY_LENGTH 4

// insert your code above here.. and as the other answer says you should
// always check malloc's return value to make sure it succeeded before
// continuing or you will seg fault. If it fails, you should gracefully
// handle the error

memcpy(b, a, sizeof(int) * ARRAY_LENGTH);  // copies sizeof(int)*ARRAY_LENGTH bytes
                                           // from the memory space pointed to by a
                                           // to the memory space pointed to by b
free(a);  // returns the memory pointed to by a to the heap

有关memcpy 的更多信息可以找到here .它是用于复制内存的高度优化的功能。如果你只有 4 个值,我怀疑你会发现你自己的循环、memcpy 或简单地手动分配(展开循环)每个值之间的性能差异,除非你运行这个数千或数百万次。

还有一点,作为一般经验法则,您希望尽可能少地使用 malloc。唯一应该使用它的情况是,如果直到运行时才知道需要多少内存,或者如果您希望内存范围在函数之外持续存在。内存管理不当是许多错误的根源,这些错误在大型程序中很难追踪,因为它们并不总是在同一时间在同一位置以相同方式出现。在这里,您没有显示足够的代码让我确切地知道您在做什么。但是你确实提前知道数组的大小(4 int),所以除非你在函数之外需要这些数组,否则只需将它们放在局部范围内(在堆栈中大多数系统):

int a[4];
int b[4];
// perform assignment to a
// perform copy to b
// do work on data
// ....
// now when the function ends, these arrays will automatically get destroyed, saving you the trouble

我相信你的话,你有充分的理由复制 a 数组,因为这在你的代码中并不明显。

最后,这是一个骗局,我们都不应该回答它 :) How to copy one integer array to another

关于c - 如何在C中将数组A的指针设置为指向数组B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39902386/

相关文章:

javascript - 来自指定数组的元素对,其总和等于特定目标数

java - 如何通过排序方法组织字符串?

c - char s[] 和 char *s 在初始化方面有什么区别?

c - 函数声明中的 __devexit 是什么意思?

c - 是否可以在另一个函数的定义中提供函数名称作为初始值设定项?

c# - 使用 LINQ 查询获取索引值的集合

c++ - 删除从 C++ 中的 void 强制转换的指针是否安全?

c - 使用 getchar() 输入字符串

c++ - 如何表示指向地址空间开头的指针?

c - 释放已分配给 char 指针(字符串)数组的内存。我必须释放每个字符串还是只释放 "main"指针?