如何将二维数组的一部分复制到一维数组中?
问题描述:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[3][3] = {
1,2,3,
4,5,6,
7,8,9
};
int *arry = (int*)malloc(3 * sizeof(int));
*arry = memcpy(arry, arr[1], 3 *sizeof(int));
int t;
for(t = 0 ; t < 3 ; t++)
{
printf("\n");
printf("%d \t", arry[t]);
}
}
是生产这样的输出:
过程返回3段(0x3)执行时间:0.011小号
按任意键继续。
为什么它不能正确复制第一个值?
答
它被正确拷贝的第一个值,但
*arry = memcpy(arry, arr[1], 3 *sizeof(int));
您正在使用的memcpy
返回值覆盖它。
只需拨打
memcpy(arry, arr[1], 3 *sizeof(int));
,或者如果你要检查它(毫无意义,因为memcpy
返回第一个参数)的返回值分配给不同的变量。
+0
感谢哇的惊人的快速,准确的响应+1 – 2013-04-04 14:53:54
+0
你应该接受的答案是正确的;) – Boumbles 2013-04-04 15:40:14
答
memcpy返回一个void *。
您正在将memcpy返回的void *赋值给arry所指向的值。尝试读取该值时,这会给你一个奇怪的值。只需调用的memcpy
memcpy(arry, arr[1], 3 * sizeof(int));
*** ***二维修正 – 2013-04-04 14:53:24
..谢谢 – 2013-04-04 14:57:32