我正在尝试从另一个数组a复制数组(temp)。但我认为这是不可能发生的。
Fig-1
int main()
{
typedef int arr_1[3];
arr_1 arr[4];
arr_1 *temp;
arr_1 a[3] = {1, 2, 3};
memset(&temp, 0, sizeof(temp));
memcpy(temp, a, sizeof(temp));
}但当我尝试下面这样的简单程序时,
Fig-2
main()
{
int abc[3], def[3];
def[3] = {1, 2, 3};
memcpy(abc, def, sizeof(abc));
}上面的代码(fig-2)对我来说工作得很好。但是fig-1不为我工作。两者几乎是一样的。但是为什么fig-1不工作呢?
发布于 2013-03-28 23:08:04
例如,您必须使用malloc()为temp分配内存。现在它只是一个未初始化的指针。
发布于 2013-03-28 23:05:35
因为temp不是数组,所以它是一个指针,因此sizeof(temp)与数组完全没有关系。
您希望将memcpy更改为使用sizeof(a)。在复制到temp之前,您还需要给它一个合理的值,否则程序会有未定义的行为。
发布于 2018-08-02 23:12:42
我知道,我迟到了。但当我读到前面的答案时,我想“你不需要所有这些变量”
使用您的简单示例:
int abc[3], def[3]; //abs is destination and def is source
def[3] = {1, 2, 3};
memcpy(abc, def, 3*sizeof(int)); //you can do sizeof(int) as you have here an array of int.但最好使用变量"const int array_size = 3“或"#define ARRAY_SIZE 3”来定义数组大小。然后你只需要将"3“替换为"ARRAY_SIZE”,它就可以做同样的工作,并避免大小错误。
对于你真正的问题,你可以这样做:
#define ARRAY_SIZE 3
typedef int arr_1[ARRAY_SIZE];
arr_1 arr[ARRAY_SIZE+1];//it is useless here
arr_1 *temp = (arr_1 *) malloc(sizeof(arr_1)); //it is your destination, but you have a pointer of array
arr_1 a[ARRAY_SIZE] = {1, 2, 3};//it is your source
//by doing sizeof((*temp)[0])
//you do not care about the type of you array pointer
//you are sure to take the good size --> it fills your array with 0
memset((*temp), 0, (ARRAY_SIZE+1)*sizeof((*temp)[0]));
//same logic
//but you destination is (*temp) because you have a pointer of array
//it means that your array arr and a have the same type
memcpy((*temp), a, ARRAY_SIZE * sizeof(a[0]));
//by the way, the las cell of arr is still 0
//and a pointer is close to an array. If you do "tmp = a;" it works.
//but it is not a copy, you just give the a's reference to tmphttps://stackoverflow.com/questions/15685240
复制相似问题