2.
开始觉得这个题目有问题 , 就是最后面的那个函数copy_ptrs(target3, source, source + 5);
后来发现题目上说,第3个函数传的参数是 最后一个元素后面的元素的指针!!
好别扭。。
#include<stdio.h> void copy_arr(double target[], double source[], int n); void copy_ptr(double * target, double * source, int n); void copy_ptrs(double *target, double * start, double* end); int main(int argc, char const *argv[]) { double source[5] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; double target1[5]; double target2[5]; double target3[5]; copy_arr(target1, source, 5); copy_ptr(target2, source, 5); copy_ptrs(target3, source, source + 5); for (int i = 0; i < 5; i++) { printf("%lf %lf %lf\n", target1[i], target2[i], target3[i]); } getchar(); return 0; } void copy_arr(double target[], double source[], int n) { for (int i = 0; i < n; i++) { target[i] = source[i]; } } void copy_ptr(double * target, double * source, int n) { for (int i = 0; i < n; i++) { *(target + i) = *(source + i); } } void copy_ptrs(double *target, double * start, double* end) { double * p_double = start; int i = 0; for (p_double = start; p_double < end; p_double++) //这个是<end,因为传递的是最后一个元素后面的元素 { target[i] = *p_double; i++; } }
3.返回int 数组最大值
#include<stdio.h> int max(int arr[], int n) { int max; max = arr[0]; for (int i = 0; i < n; i++) { if (max < arr[i]) max = arr[i]; } return max; } int main() { const int N = 10; int arr_int[N] = { 1,2,3,4,5,6,7,8,9,10 }; printf("max = %d", max(arr_int, N)); getchar(); return 0; }
4.5 略
6.将double数组倒序排列。
#include<stdio.h> void sort(double arr[], int index) { for (int i = 0; i < index-1; i++) { for (int j = 0; j < index - i ; j++) { if (arr[j] < arr[j + 1]) { double tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } } int main(void) { double arr[10] = { 7,8,6,1,2,5,4,3,9,10 }; sort(arr, 10); for (int i = 0; i < 10; i++) printf("%g\n", arr[i]); getchar(); return 0; }
后面的多数设计变长数组,而很多编译器并支持,所以略。