我一直在学习数组,但有一件事我想不通。 借了两本C的书,上网查了一下,没有找到解决办法。
我的函数 timesTen 将我拥有的每个数组元素乘以 10, 然后返回该数组返回函数 main() 的指针
如何将数组 a[2] 直接复制到数组 x[2] 中?
我通常会使用 for 循环,但我不能,因为参数在两个不同的函数中。
解决方案可能与指针有关,所以请随意在此处发布解决方案,但是还有什么办法可以绕过它们吗?
源代码如下:
#include <stdio.h>
int timesTen(int a[])
{
int i;
for (i=0;i<2;i++)
{
printf("%d\t", a[i]);
a[i]*=10;
printf("%d\n", a[i]);
}
return a;
}
int main()
{
int i;
int x[2];
int a[2]={10,50};
// i know here's an error, but how do I fix it? I cant put x[0]=timesTen(a[0])
x[2] = timesTen(a);
//also what if there is array a[10], and I want to copy it in x[5]
for (i=0;i<2;i++)
printf("%d\n", x[i]);
return 0;
}
谢谢!
最佳答案
你需要明白的是数组和指针的区别。当您在 main()
中声明两个数组时,您为两个整数分配了两倍的内存。没关系。但是在 C 中,您根本无法传递数组(如:隐式分配新的内存并将源数组的数据复制到该内存区域)。相反,在几乎所有情况下,任何数组标识符都会退化为指向数组第一个元素的指针。所以当你写
int x[2];
int a[2]={10,50};
timesTen(a);
这段代码正好等同于
int x[2];
int a[2]={10,50};
timesTen(&a[0]);
那么,为什么这不会与您的 timesTen()
声明冲突?因为函数声明中的数组参数当场衰减为指针!所以,你的函数声明正好等同于这个:
int timesTen(int* a) {
这是 C 语言中最难理解的特性之一,诚然,您很难全神贯注于此,但是一旦您理解了指针衰减的含义,您就会更加轻松地使用指针和数组。
所以,回到你的问题。由于您只将指向您的数组的指针传递给 timesTen()
,并且由于您修改了该数组,所以更改在 main()
中直接可见。有两种方法可以实现您想要的行为:
您可以更改
timesTen()
的定义以将数据复制到目标数组中:void timesTen(int size, int* source, int* dest) { for(int i = 0; i < size; i++) dest[i] = 10*source[i]; } int main() { int x[2]; int a[2]={10,50}; timesTen(2, a, x); //pointer decay! //x now contains {100, 500} }
您可以在调用函数修改目标数组之前将数据复制到目标数组中:
void timesTen(int size, int* data) { for(int i = 0; i < size; i++) data[i] = 10*data[i]; } int main() { int x[2]; int a[2]={10,50}; memcpy(x, a, sizeof(a)); //the sizeof operator is one of only two places where no pointer decay happens! timesTen(2, x); //pointer decay! //x now contains {100, 500} }
关于c - 如何将返回的数组直接复制到另一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21952882/