我有一個需求,我需要將一個空數組作爲參數傳遞給一個函數。在這個被調用的函數中,我應該將一些數據存入傳入的數組中。所以我寫了一個與我的要求相同的小例子。下面是它的代碼:memcpy一個緩衝區和一個陣列不工作
#include <stdio.h>
#include <stdlib.h>
void printArr(int *a)
{
int i;
int *b=(int*)malloc(sizeof(int)*10);
printf("\n\nEnter 10 lements:\n");
for(i=0;i<10;i++)
scanf("%d",&b[i]);
printf("\nContents of array b:\n");
for(i=0;i<10;i++)
printf("%d\t",b[i]);
printf("\n");
memcpy(a,b,10);
printf("\nContents of array a:\n");
for(i=0;i<10;i++)
printf("%d\t",a[i]);
printf("\n");
}
int main()
{
int a[10];
printArr(a);
return 0;
}
在上面的例子中,我發送一個數組從主函數到printArr函數。現在在被調用函數中,數據將被memcpy插入到數組中。當打印數組內容時,我得到一些垃圾值。另外,編譯給予警告,如下圖所示:
$ gcc -o arr array.c
array.c: In function ‘printArr’:
array.c:15:2: warning: incompatible implicit declaration of built-in function ‘memcpy’
上述程序的輸出如下圖所示:
Enter 10 lements:
0 1 2 3 4 5 6 7 8 9
Contents of array b:
0 1 2 3 4 5 6 7 8 9
Contents of array a:
0 1 134479874 11136160 11136160 11132916 134514160 134513696 134514171 11132916
有人能告訴我什麼是錯在上面的程序。
注意:我需要將數據從緩衝區複製到傳遞數組,只使用memcpy而不是通過for循環,因爲在我的實際程序中的性能原因。
在此先感謝。
完美....感謝很多工作完美罰款。我會在10分鐘內接受你的回答。但爲什麼string.h是必需的? – Zax
@Zax對於'memcpy'原型。包括string.h在內的 – cnicutar
甚至刪除了警告。謝謝。 – Zax