Small program that uses pointers to sum integers

痞子三分冷 提交于 2021-02-08 12:01:19

问题


I need to create a program which calculates the cumulative sum of a dynamically allocated vector and the vector should be filled with random values (not values from stdin) ​​using only pointers. I couldn't think of a version that uses only pointers (i'm kinda new to this matter).

This is the code I have so far:

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

回答1:


It's not something that much more complicated, instead of declaring int variables you need to declare int pointers and then allocate memory for them.

Something like:

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

EDIT

Added random number generation instead of stdin values




回答2:


You can use something like this instead of static variable

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}


来源:https://stackoverflow.com/questions/60882913/small-program-that-uses-pointers-to-sum-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!