Advertisement
KuoHsiangYu

使用malloc於執行期間動態決定陣列長度

Mar 2nd, 2019
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.70 KB | None | 0 0
  1. /*
  2. Windows 10 作業系統
  3. Visaul Studio 2017
  4. */
  5. #define _CRT_SECURE_NO_WARNINGS
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. int main(int argc, char *argv[]) {
  11.     system("color f0");
  12.  
  13.     int size = 0, sum = 0;
  14.  
  15.     printf("Enter array size : ");
  16.     scanf("%d", &size);
  17.  
  18.     int *array = NULL;
  19.     array = (int*)malloc(size * sizeof(int));
  20.  
  21.     if (NULL == array) {
  22.         printf("Error, memory access failure.\n");
  23.         system("pause");
  24.         return -1;
  25.     }
  26.     else {
  27.         for (int i = 0; i < size; i++) {
  28.             printf("Input array[i] value : ");
  29.             scanf("%d", &array[i]);
  30.         }
  31.         for (int i = 0; i < size; i++) {
  32.             sum = sum + array[i];
  33.         }
  34.         printf("sum = %d\n", sum);
  35.     }
  36.     free(array);
  37.  
  38.     system("pause");
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement