首页 > 解决方案 > 使用指针对整数求和的小程序

问题描述

我需要创建一个程序来计算动态分配的向量的累积和,并且向量应该用随机值(不是标准输入中的值)填充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;
}

标签: cpointerssummallocdynamic-arrays

解决方案


这不是更复杂的事情,而不是声明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;
}

编辑

添加了随机数生成而不是标准输入值


推荐阅读