数组结合指针可以实现很多有趣的功能,比如下面这个程序:
假设数组为 : 12345
如果左移一次即为:23451 ,依次类推
如果右移一次即为:51234 ,依次类推
翻转则为:54321
我们来实现下这个程序:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define NR(x) (sizeof(x)/sizeof(x[0]))
- //数组左移
- int buffer_left_move(int *buffer , int buf_len)
- {
- int i ;
- char tmp = buffer[0];
- for(i = 1 ; i < buf_len ; i++)
- {
- buffer[i-1] = buffer[i] ;
- }
- buffer[buf_len-1] = tmp ;
- }
- //数组右移
- int buffer_right_move(int *buffer , int buf_len)
- {
- int i ;
- char tmp = buffer[buf_len - 1];
- for(i = buf_len ; i > 0 ; i--)
- {
- buffer[i] = buffer[i-1] ;
- }
- buffer[0] = tmp ;
- }
- //数组翻转
- int buffer_turn_over(int *buffer , int buf_len)
- {
- int size = buf_len ;
- int i , tmp;
- for(i = 0 ; i < size/2 ; i++)
- {
- tmp = buffer[i] ;
- buffer[i] = buffer[size-1-i] ;
- buffer[size-1-i] = tmp;
- }
- }
- //打印数组
- void print_buffer(int *buffer, int buf_len)
- {
- int i ;
- system("cls");
- printf("please input \'a' or \'b' or \'w' \n");
- for(i = 0 ; i < buf_len ; i++)
- {
- printf("%d",buffer[i]);
- }
- putchar('\n');
- }
-
- int main(void)
- {
- int buffer[5] = {1,2,3,4,5} ;
-
- print_buffer(buffer,NR(buffer));
- while(1)
- {
- switch(getch())
- {
- //左边
- case 'a':
- buffer_left_move(buffer,NR(buffer)) ;
- print_buffer(buffer,5);
- break ;
- //右边
- case 'd':
- buffer_right_move(buffer,NR(buffer));
- print_buffer(buffer,5);
- break ;
- //翻转
- case 'w':
- buffer_turn_over(buffer,NR(buffer)) ;
- print_buffer(buffer,5);
- break ;
- }
- }
- return 0 ;
- }
复制代码
运行结果:
please input 'a' or 'b' or 'w'
12345
按下a为不断左移,按下d为不断右移,按下w则为翻转 |