Search code examples
ccs50

Why do I have to use * in sum += *(total_sum + counter);?


So inside of the first loop, we intend to record new inputs to new memory locations if so why we didn't put an asterisk or ampersand to total_sum + limit_reaching?

My second question is why there's an * in sum += *(total_sum + counter); but not an &?

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

int main(void)
{
    int size_of_sum;
    printf("Enter total amount of numbers you want to sum up : ");
    scanf("%d", &size_of_sum);

    int total_sum;
    total_sum = (int*) malloc (size_of_sum * sizeof(int));

    for(int limit_reaching = 0; limit_reaching < size_of_sum; limit_reaching++)
    {
        printf("Enter a number : ");
        scanf("%d", total_sum + limit_reaching);
    }

    int sum = 0;
    for(int counter = 0; counter < size_of_sum; counter++)
    {
         sum += *(total_sum + counter);
    }

    printf("Sum : %d\n", sum);

    free(total_sum);
}

I want to learn what are the roles of * in this code.


Solution

  • I'm surprsied this compiles:

        int total_sum;
        total_sum = (int*) malloc (size_of_sum * sizeof(int));
    

    You really meant to dynamically allocate an array and declare total_sum as a pointer, right? That's got to be a typo.

    Better:

        int* total_sum;
        total_sum = (int*) malloc (size_of_sum * sizeof(int));
    

    Here, total_sum is a pointer. Or more canonically, it's understood to be an array of integer of length size_of_sum.

    In C, I believe you can get away with just declaring this instead of doing a malloc (and hence, skip the free call).

    int total_sum[size_of_sum];
    

    Either way, total_sum whether formally a pointer or an array, is logically treated like a pointer for most purposes in code.

    So when you say:

    total_sum + counter
    

    That's equivalent to this expression:

    &total_sum[counter]
    

    Both expressions are a pointer to the position of an integer within that array (pointer).

    If you want the value of that integer, you express that in code as either:

    *(total_sum + counter)
    

    The * means, "give me the value at this pointer address".

    Or simply:

    total_sum[counter]
    

    Both approaches work regardless if you declared total_sum to be a malloc'd pointer or as an array.