$0.16

What's the difference between these two code?

Ask a question+
0
`#include <stdio.h>
int arraySum(int arr[], int n)
{
    int sum = 0;
    int i;
    for(i = 0; i < n; i++)
    {
        sum += arr[i];
    }
    return sum;
}
int main()
{
    int a[3] = {1,2,4};
    printf("The sum is %d",arraySum(a,3));

}

and …

#include <stdio.h>
int arraySum(int array[],const int n)
{
    int sum = 0;
    int *ptr;
    int *const arrayEnd = array + n;
    for(ptr = array; ptr <arrayEnd; ++ptr)
    {
        sum += *ptr;
    }
    return sum;
}
int main()
{
    int values[10] = {3,-2,3};
    printf("The sum is %d",arraySum(values,10));


}

`

slamsal 10
add comment

1 Answer

0

The first one is a basic implementation of the function. The second one is a more advanced way of doing the same thing using pointers (Pointer specific operators are * (dereference operator) and & (address-of operator)).

I don’t know a ton about pointers, but I will try to explain what the second one is doing and why it works:
To start, an array is technically a pointer. In your code, you have int values[10] = {3,-2,3}; the variable values now points to the address in memory where the beginning of the array is. When you defined ptr like int *ptr; this allow it to hold the address of some value.
In your code, int *const arrayEnd = array + n Using the * it accesses the addres where the array starts and then by adding n which holds the length of the array it holds the address of where the array ends. And when comparing the two variables like: ptr < arrayEnd it will be true when ptr is referencing an address before the address of the end.
Using ++ptr is the same as ptr++ which is just a shortcut for ptr = ptr + 1 which in our case will set ptr to the next address of memory.
Because * is the dereference operator we use that to access the data at that location in memory, which allows us to add it to sum.

I hope this explaination made sense to you and wasn’t too boring. If this doesn’t answer your question please ask for clarification.

Dark Vortex 0
add comment

Your Answer