#include <stdlib.h> #include <stdio.h> #include <string.h> //二維整型數組打印顯示 void printarr2d(int (*a)[3],int row,int col) { int i,j; for(i=0; i<row; i++) { for(j=0; j<col; j++) { printf("%d ", a[i][j]); } printf("\n"); } }
main()
{
int i,j;
int a[2][3]={{1,2,3},{4,5,6}};
int b[2][3];
//二維數組複製(第三個參數爲數組總的字節數)
memcpy(b,a, 2*3*sizeof(int) );//memcpy(&b[0][0],&a[0][0],24);
//二維數組打印顯示 (before zero)
printarr2d(b,2,3);
//二維數組清零
memset(b,0, 2*3*sizeof(int) );
//二維數組打印顯示 (after zero)
printarr2d(b,2,3);
system("pause");
return 0;
}數組
c語言中如何複製一個二維數組的全部元素的值到另一個二維數 使用for循環當然能夠,可是總感受很是麻煩 #include"stdio.h" int main(void) { int i,j; int a[2][5]={{1,2,3},{4,5,6,8}}; int b[2][5]; for(i=0;i<2;i++) { for(j=0;j<5;j++) { b[i][j]=a[i][j]; } } printf("%d",b[1][2]); } (1)
mencpy的原型是void *memcpy(void *dest, const void *src, size_t n); 1 爲何*memcpy這裏前面有個*號?? 2 爲何函數的參數裏面void * src 前面有個修飾符const 答: 1: memcpy 返回值爲void * 2:加 const 變爲常量指針 防止在memcpy中對src指向的內容進行修改,函數的健壯性考慮
本身作的時候,就在想,如何不適用二重for循環的辦法,對二維數組進行復制操做函數
看了下CSDN 的bbs結果然的有,很是感謝spa
注:指針
1)使用memcpy函數,memset函數都要引入庫文件 #include <string.h>code
2)原本想對這個複製函數封裝的,後來感受不必,直接使用,只不過要注意第三個參數爲:數組總體內存所佔bit數,要當心blog
(2)內存
memset(b,0, 2*3*sizeof(int) );
第一個值是數組地址,第二個是你要把數組中的值賦爲多少,第三個是你要賦多少個元素。
總結版:原型
二維數組複製:string
//二維數組複製(第三個參數爲數組總的字節數) memcpy(b,a, 2*3*sizeof(int) );//memcpy(&b[0][0],&a[0][0],24);
二維數組清零:it
//二維數組清零 memset(b,0, 2*3*sizeof(int) );