如何将一个数组赋值给另一个数组,用C代码演示
时间: 2023-09-26 08:07:40 浏览: 59
可以使用循环遍历的方式将一个数组赋值给另一个数组。以下是一个示例的C代码:
```c
#include <stdio.h>
void copyArray(int source[], int destination[], int size) {
for (int i = 0; i < size; i++) {
destination[i] = source[i];
}
}
int main() {
int sourceArray[] = {1, 2, 3, 4, 5};
int destinationArray[5];
// 调用函数进行数组赋值
copyArray(sourceArray, destinationArray, 5);
// 打印目标数组
for (int i = 0; i < 5; i++) {
printf("%d ", destinationArray[i]);
}
printf("\n");
return 0;
}
```
在上面的代码中,我们定义了一个`copyArray`函数,它接受三个参数:源数组`source`、目标数组`destination`和数组的大小`size`。函数使用循环遍历源数组,并将每个元素复制到目标数组的相应位置。
在主函数中,我们声明了一个源数组`sourceArray`和一个目标数组`destinationArray`。然后,我们调用`copyArray`函数将源数组赋值给目标数组。最后,我们使用循环打印出目标数组的内容。
运行上述代码将输出:`1 2 3 4 5`,表示成功将源数组赋值给了目标数组。