Task Description(請先在-72題那邊看完題目與測資後再回來此題)
Write a program to fill an array with integers. We will be given an array ptr of n pointers to integers. The first element of ptr points to the first element in an integer array, and the last element of ptr points to the last element. Now we need to write an integer to every element of this integer array according to the following rules.
If an integer in the array is pointed by a pointer within the array ptr, then its value should be the index of that pointer within the array.
If an integer in the array is not pointed by a pointer within the array ptr, its value should be the sum of the two values of the two nearest elements to its left and to its right in the array that are pointed by pointers within the array ptr.
You should implement the following function to assign values according to description above. The parameter ptr is the array of pointers, and n is the number of pointers in ptr. You only need to write the fill_array function.
fill_array.h
打上 function header 以及相關的設定。
1 2 3 4 | #include <stdio.h>
#include <stdlib.h>
void fill_array( int **ptr, int n, int *arr, int m);
|
fill_array.c
撰寫程式碼後對應上傳。
1 2 3 4 5 | #include "fill_array.h"
void fill_array( int **ptr, int n, int *arr, int m) {
/ add your code /
}
|
main.c
這個檔案無法更改也無須上傳。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include "fill_array.h"
int main() {
int n = 0, m = 0;
scanf ( "%d %d" , &n, &m);
int *A = malloc (n * sizeof ( int ));
int *arr = malloc (m * sizeof ( int ));
for ( int i = 0; i < m; i++) {
arr[i] = -1;
}
int **ptr = malloc (n * sizeof ( int *));
for ( int i = 0; i < n; i++) {
scanf ( "%d" , &A[i]);
ptr[i] = &arr[A[i]];
}
fill_array(ptr, n, arr, m);
for ( int i = 0; i < m; i++) {
printf ( "%d" , arr[i]);
if (i != m-1) printf ( " " );
else printf ( "\n" );
}
free (A);
free (arr);
free (ptr);
return 0;
}
|