1

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.

1
  • Oops, I would advise not to retry after a memory allocation unless you made sure to have freed something. As memory is now a cheap thing, most applications or libraries are not well prepared to face a memory allocation error. So when it happens the best is to close everything before the kernel panics. Commented Nov 27, 2020 at 9:32

2 Answers 2

2

You have a few errors in your program:

  1. The loop condition in the do-while loop should be flag == 0. With flag = 0 you assign zero to flag and the loop never repeats.

  2. The assignment should be

    newarray = PartialSums(arrsize, array);
    

    That is, without pointer dereference.

  3. As pointed out by WhozCraig you have a memory leak when newarray is assigned the result of PartialSums; you don't need to allocate memory for newarray in the main function.

You should also make sure that the input is valid by inspecting the return value of scanf. It is also a good idea to print a newline after the result to make sure it is displayed correctly also on non-Windows systems.

Tip: When working with dynamically allocated arrays it is useful to keep the name of an array and its length together. Therefor I always use the array name with the suffix Len for an array length variable. In your case it would be arrayLen and newarrayLen. With this approach you never mix up different array lengths (even though in this program there is only one length).

Sign up to request clarification or add additional context in comments.

2 Comments

And fix the memory leak once you fix the second. The allocation for newarray= (int*) malloc(... in main is pointless; the PartialSums function does it for you.
thanks that worked, i didn't even noticed i assigned in the do-while insted of condition and malloc twice on newarray
0

There are multiple errors:

  • the logic for the do / while loop is broken: the test flag = 0 sets flag to 0 instead of comparing to 0. Furthermore, you must set flag to 1 inside the loop. It is actually simpler to use a for(;;) loop and explicitly break from it if you can allocate the array.
  • it serves no purpose to allocate newarray in main().
  • memory allocation failure should be tested in PartialSums.
  • storing the return value from PartialSums should be just newarray = PartialSums(arrsize,array); As coded, you are patching the first entry of the newarray you allocated in main(), which explains the observed behavior.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>

int *PartialSums(int arrsize, int *array) {
    int *newarray = (int *)malloc(arrsize * sizeof(int));
    if (newarray != NULL) {
        int sum = 0;
        for (int i = 0; i < arrsize; i++) {
            sum = sum + array[i];
            newarray[i] = sum;
        }
    }
    return newarray;
}

int flush_input(void) {
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        continue;
    return c;
}

int main() {
    int *array;
    int *newarray;
    int arrsize;
    for (;;) {
        printf("please insert amount of numbers to enter:\n");
        if (scanf("%d", &arrsize) != 1 || arrsize <= 0) {
            printf("invalid input\n");
            if (flush_input() == EOF)
                return 1;
            continue;
        }
        array = (int *)malloc(arrsize * sizeof(int));
        /* if memory cannot be allocated */
        if (array == NULL) {
            printf("Error! memory not allocated.\n\n");
        } else {
            break;
        }
    }

    for (int i = 0; i < arrsize;) {
        printf("please insert a number for array[%d]: ", i);
        if (scanf("%d", &array[i]) == 1) {
            i++;
        } else {
            printf("invalid input\n");
            if (flush_input() == EOF)
                return 1;
        }
    }
    printf("This is the main array: ");
    printf("%d", array[0]);
    for (int i = 1; i < arrsize; i++) {
        printf(",%d", array[i]);
    }
    printf("\n");

    newarray = PartialSums(arrsize, array);
    if (newarray) {
        printf("This is the new array: ");
        printf("%d", newarray[0]);
        for (int i = 1; i < arrsize; i++) {
            printf(",%d", newarray[i]);
        }
        printf("\n");
        free(newarray);
    } else {
        printf("Memory allocation failure\n");
    }
    free(array);
    return 0;
}

2 Comments

i never seen a for (;;) looks like that, how do you work with it without the assignment and condition inside?
for(;;) is a for ever loop: no condition means no ending condition. This loop will continue until explicitly broken from with a break or return statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.