我有一个要求,我需要将一个空数组作为参数传递给一个函数.在这个被调用的函数中,我应该将一些数据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;
}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我将一个数组从main函数发送到printArr函数.现在在被调用的函数中,数据将被存储到数组中.当打印数组内容时,我得到一些垃圾值.此外,编译会发出警告,如下所示:
$ gcc -o arr array.c
array.c: In function ‘printArr’:
array.c:15:2: warning: incompatible implicit declaration of built-in function ‘memcpy’
Run Code Online (Sandbox Code Playgroud)
上述程序的输出如下所示:
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
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我上面的程序有什么问题.
注意:由于实际程序中的性能原因,我需要仅使用memcpy而不是通过for循环将数据从缓冲区复制到传递数组.
提前致谢.
cni*_*tar 12
memcpy(a,b,10);
Run Code Online (Sandbox Code Playgroud)
第三个参数是要复制的字节数.你想要的memcpy(a, b, 10 * sizeof *a).
此外,你错过了#include <string.h>,这就是你得到警告的原因.
该 memcpy()函数的用法如下:
void * memcpy ( void * destination, const void * source, size_t num );
Run Code Online (Sandbox Code Playgroud)
其中num是多个字节.
为了解决这个问题,您需要按以下方式使用它:
memcpy(a,b,10*sizeof(int));
Run Code Online (Sandbox Code Playgroud)
因为通常整数的大小是4字节(取决于平台,编译器等).
在您的程序中,您只复制10字节而不是40字节.因此,在这种情况下,您将获得2,5在数组中初始化的第一个" "元素a[],其余元素包含垃圾.
编辑:你也忘了#include <string.h>,所以这会导致以下编译警告:
array.c:15:2:警告:内置函数'memcpy'的不兼容隐式声明
对于将来,请注意编译器警告,因为它可以避免大量的运行时错误.
| 归档时间: |
|
| 查看次数: |
13051 次 |
| 最近记录: |