[圖解C] Example 719: dynamic allocation of an 1-D array

// Example 719: dynamic allocation of an 1-D array

// way 1: type *pointer = (type*)malloc(length*sizeof(type));

// way 2: type *pointer;
//        pointer = (type*)malloc(length*sizeof(type));

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *grade, n, sum=0;
    int i;
 
    printf("the number of students, n = ");
    scanf("%d", &n);   // thus *grade is an 1xn array
 
    // dynamic allocation
    grade = (int*)malloc(n*sizeof(int));
    printf(" there is %d students.\n", n);
    printf("\n");
 
    for (i=0 ; i<n ; i++){
        printf("enter the %d th studend's grade: ");
        scanf("%d", &grade[i]);
        sum += grade[i];
        // pointer grade can represent adress and value
        // dep on %p or %d
    }
    printf("\n");
 
    printf("ID \t Grade\n");
    for (i=0 ; i<n ; i++){
        printf("%d \t %d\n", i, grade[i]);
        // pointer grade represent value by %d
    }
    printf("\n");
 
    printf("the average is: %.2f\n", (float)sum/(float)n);
 
    // release the memory of the pointer, grade
    free(grade);
 
    system("pause");
    return 0;
}