使用指针对整数求和的小程序

Small program that uses pointers to sum integers

我需要创建一个程序来计算动态分配向量的累加和,该向量应该用随机值填充(不是来自标准输入的值)使用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 main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

这并没有那么复杂,您需要声明 int 个指针,然后为它们分配内存,而不是声明 int 个变量。

类似于:

Running sample

#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;
}

编辑

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