c - 使用指针对整数求和的小程序
问题描述
我需要创建一个程序来计算动态分配的向量的累积和,并且向量应该用随机值(不是标准输入中的值)填充only pointers
。我想不出只使用指针的版本(我对这件事有点陌生)。
这是我到目前为止的代码:
#include <stdio.h>
#include <malloc.h>
int main()
{
int i, n, sum = 0;
int *a;
printf("Define size of your array A \n");
scanf("%d", &n);
a = (int *)malloc(n * sizeof(int));
printf("Add the elements: \n");
for (i = 0; i < n; i++)
{
scanf("%d", a + i);
}
for (i = 0; i < n; i++)
{
sum = sum + *(a + i);
}
printf("Sum of all the elements in the array = %d\n", sum);
return 0;
}
解决方案
这不是更复杂的事情,而不是声明int
变量,您需要声明int
指针然后为它们分配内存。
就像是:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int *n = malloc(sizeof(int)); //memory allocation for needed variables
int *sum = malloc(sizeof(int));
int *a;
srand(time(NULL)); //seed
printf("Define size of your array A \n");
scanf("%d", n);
if (*n < 1) { //size must be > 0
puts("Invalid size");
return 1;
}
printf("Generating random values... \n");
a = malloc(sizeof(int) * *n); //allocating array of ints
*sum = 0; //reseting sum
while ((*n)--) {
a[*n] = rand() % 1000 + 1; // adding random numbers to the array from 1 to 1000
//scanf("%d", &a[*n]); //storing values in the array from stdin
*sum += a[*n]; // adding values in sum
}
printf("Sum of all the elements in the array = %d\n", *sum);
return 0;
}
编辑
添加了随机数生成而不是标准输入值
推荐阅读
- java - Jakarta Server Pages 找不到属性
- angular - 我可以将 netlify 环境变量添加到我的 Angular 应用程序吗?
- sql - Big Query 在最近日期加入
- javascript - 有没有更好的方法来(取消)选择 HighCharts LineChart 中的所有 LegendItems?
- rabbitmq - 如何从外部秘密设置兔子密码?
- c - 函数中的 Free() 函数使我的整个程序在 c 中崩溃
- sql - 空数组在 PostgreSQL 中是否等于 NULL,还是里面有 NULL 的数组?
- python - 合并具有不同键列的两个表
- spring-boot - Liquibase 无法正确启动
- jdbc - 带有 Cosmos db 的石英