c语言结构体数组循环右移
时间: 2024-03-13 07:40:32 浏览: 32
C语言中的结构体数组循环右移是指将数组中的元素向右移动指定的位置,并且最后一个元素移动到数组的开头。下面是一个实现结构体数组循环右移的示例代码:
```c
#include <stdio.h>
#define SIZE 5
typedef struct {
int id;
char name[20];
} Student;
void rightShift(Student arr[], int n, int shift) {
Student temp[SIZE];
int i;
// 将要移动的元素保存到临时数组中
for (i = 0; i < shift; i++) {
temp[i] = arr[n - shift + i];
}
// 将数组中的元素向右移动
for (i = n - 1; i >= shift; i--) {
arr[i] = arr[i - shift];
}
// 将临时数组中的元素放回原数组的开头
for (i = 0; i < shift; i++) {
arr[i] = temp[i];
}
}
int main() {
Student students[SIZE] = {
{1, "Alice"},
{2, "Bob"},
{3, "Charlie"},
{4, "David"},
{5, "Eve"}
};
int i;
printf("原始数组:\n");
for (i = 0; i < SIZE; i++) {
printf("ID: %d, Name: %s\n", students[i].id, students[i].name);
}
rightShift(students, SIZE, 2);
printf("\n循环右移后的数组:\n");
for (i = 0; i < SIZE; i++) {
printf("ID: %d, Name: %s\n", students[i].id, students[i].name);
}
return 0;
}
```
在上面的代码中,我们定义了一个结构体类型`Student`,包含了学生的ID和姓名。然后我们定义了一个`rightShift`函数,该函数接受一个结构体数组、数组的大小和要右移的位置作为参数。函数内部使用一个临时数组`temp`来保存要移动的元素,然后通过循环将数组中的元素向右移动,并将临时数组中的元素放回原数组的开头。最后,在`main`函数中我们创建了一个包含5个学生信息的结构体数组,并调用`rightShift`函数将数组循环右移2个位置。最后打印出移动后的数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![torrent](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)