#include<stdio.h>
#include<malloc.h>
int main()
{
int n;
int val;
int * a;
int sun = 0, i;
printf("請輸入陣列的長度:");
scanf("%d", &n);
printf("\n");
a = (int *)malloc(n * sizeof(int));//為陣列a動態分配記憶體
for(i = 0; i < n; i++)
printf("請輸入陣列的第%d個元素的值:", i+1);
scanf("%d", &val);
a[i] = val;
}
for (i = 0; i < n; i++)
sun+=a[i];//sun+=a[i]相當於sun=sun+a[i];
printf("sun = %d\n",sun);
free(a);//釋放a動態分配的記憶體
return 0;
#include<stdio.h>
#include<malloc.h>
int main()
{
int n;
int val;
int * a;
int sun = 0, i;
printf("請輸入陣列的長度:");
scanf("%d", &n);
printf("\n");
a = (int *)malloc(n * sizeof(int));//為陣列a動態分配記憶體
for(i = 0; i < n; i++)
{
printf("請輸入陣列的第%d個元素的值:", i+1);
scanf("%d", &val);
printf("\n");
a[i] = val;
}
for (i = 0; i < n; i++)
{
sun+=a[i];//sun+=a[i]相當於sun=sun+a[i];
}
printf("sun = %d\n",sun);
free(a);//釋放a動態分配的記憶體
return 0;
}