I have a code I wrote, basically what it does is get the size of a dynamic array named array and numbers to insert to it from the user, then send the array to the function PartialSums.
PartialSums is supposed to take the number from array[i], add it to sum, then put sum in newarray[i], until the end of the array which is arraysize, after that it should return newarray back to main and print both of the arrays.
I guess you can think of it as kind of factorial of each cell of array with the cells before but it sums the numbers instead of multiply them.
Example for what should be in newarray at the end:
arraysize = 5
array = 1,2,3,4,5
newarray should be: 1,3,6,10,15
just to show what it looks like mathematically: 1,2+1,3+2+1,4+3+2+1,5+4+3+2+1
and this is the code:
#include <stdio.h>
#include <stdlib.h>
int *PartialSums(int arrsize, int *array) {
int *newarray;
int sum = 0;
int i;
newarray = (int *)malloc(arrsize * sizeof(int));
for (i = 0; i < arrsize; i++) {
sum = sum + array[i];
newarray[i] = sum;
}
return newarray;
}
int main() {
int *array;
int *newarray;
int arrsize;
int num;
int flag = 1;
int i;
do {
printf("please insert amount of numbers to enter\n");
scanf("%d", &arrsize);
array = (int *)malloc(arrsize * sizeof(int));
newarray = (int *)malloc(arrsize * sizeof(int));
/* if memory cannot be allocated */
if (array == NULL || newarray == NULL) {
printf("Error! memory not allocated.\n\n");
flag = 0;
}
} while (flag = 0);
for (i = 0; i < arrsize; i++) {
printf("please insert a number: ");
scanf("%d", &num);
array[i] = num;
}
*newarray = PartialSums(arrsize, array);
printf("this is the main array: ");
for (i = 0; i < arrsize; i++) {
printf("%d", array[i]);
if (i < arrsize - 1)
printf(",");
}
printf("\nthis is the new array: ");
for (i = 0; i < arrsize; i++) {
printf("%d", newarray[i]);
if (i < arrsize - 1)
printf(",");
}
free(array);
free(newarray);
return 0;
}
up until the sum part everything works but for some reason the print is this:
this is the new array: 18825296,0,0,0,0
the first number changes every time
I am guessing the problem is in the function, which means something is wrong with inserting sum to newarray
or its something with returning newarray back to main
the problem is I don't know what I did wrong and hope you guys can help me understand.