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