1、使用malloc分配内存
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
// 分配内存空间
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return -1;
}
// 读取输入
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 计算总和
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of the %d integers is: %d\n", n, sum);
// 释放内存
free(arr);
return 0;
}
2、使用calloc分配内存(初始化为0)
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
// 分配内存空间并初始化为0
int *arr = (int *)calloc(n, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return -1;
}
// 读取输入
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 计算总和
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of the %d integers is: %d\n", n, sum);
// 释放内存
free(arr);
return 0;
}
3、使用静态数组(固定大小)
#include <stdio.h>
int main() {
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
int arr[n]; // 静态数组
// 读取输入
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// 计算总和
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of the %d integers is: %d\n", n, sum);
return 0;
}
4、使用动态分配数组的指针
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
// 分配内存空间
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return -1;
}
// 读取输入
printf("Enter %d integers:\n", n);
int *ptr = arr;
for (int i = 0; i < n; i++, ptr++) {
scanf("%d", ptr);
}
// 计算总和
int sum = 0;
ptr = arr;
for (int i = 0; i < n; i++, ptr++) {
sum += *ptr;
}
printf("Sum of the %d integers is: %d\n", n, sum);
// 释放内存
free(arr);
return 0;
}
5、使用动态分配数组的指针(优化写法)
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
// 分配内存空间
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return -1;
}
// 读取输入并计算总和
int sum = 0;
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum of the %d integers is: %d\n", n, sum);
// 释放内存
free(arr);
return 0;
}