用memcpy函数赋值数组中间某段数据,写个例程
时间: 2023-07-12 16:26:36 浏览: 55
可以使用以下代码示例来使用memcpy函数赋值数组中间某段数据:
```c
#include <stdio.h>
#include <string.h>
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int start = 2;
int end = 5;
int len = end - start + 1;
int temp[len];
// 使用memcpy函数将arr数组中下标从start到end的数据复制到temp数组中
memcpy(temp, arr + start, len * sizeof(int));
// 打印temp数组中的数据
printf("temp数组中的数据为:");
printArray(temp, len);
// 修改temp数组中的数据
for (int i = 0; i < len; i++) {
temp[i] = i + 1;
}
// 使用memcpy函数将temp数组中的数据复制回arr数组中
memcpy(arr + start, temp, len * sizeof(int));
// 打印修改后的arr数组中的数据
printf("修改后的arr数组中的数据为:");
printArray(arr, 10);
return 0;
}
```
运行结果如下:
```
temp数组中的数据为:3 4 5
修改后的arr数组中的数据为:1 2 1 2 3 4 5 8 9 10
```
在此示例中,我们使用memcpy函数将arr数组中下标从start到end的数据复制到temp数组中,并打印temp数组中的数据。然后,我们修改temp数组中的数据,并使用memcpy函数将temp数组中的数据复制回arr数组中,并打印修改后的arr数组中的数据。