Trouble Creating a Function to Calculate the Sum of an Array Using Pointers in C [closed]

I’m currently learning about pointers in C, and I’m facing some difficulties in creating a function that calculates the sum of an array using pointers. While I intend to return the sum of the array, it seems like I’m getting an address instead. I’m uncertain about what I’m doing wrong in my code.

Here’s a snippet of my code for reference:

#include <stdio.h>

int sum(int *arr, int size);

int main() {
    printf("Enter size of Array: ");
    int size;
    scanf("%d", &size);
    printf("Enter %d values: ", size);

    int nums[size];
    for (int i = 0; i < size; i++)
        scanf("%d", (nums+1));

    int sum_result = sum(nums, size);
    printf("the sum of the array is %d\n", sum_result); 

    return 0;
}

int sum(int *arr, int size) {

    int sum = 0, *p;
    for(p = arr; p <= arr + size; p++)
        sum += *p;

    return sum;
}

  • 5

    p <= arr + size -> p < arr + size ;;; scanf("%d", (nums+1)); -> scanf("%d", (nums+i));

    – 




  • Use p < arr + size; you reading one entry beyond the end of the array.

    – 




Leave a Comment