首页 > 解决方案 > getting error on passing array to function in C

问题描述

I have tried to use function to calculate the sum of elements in array. Logic is correct but I think there is some syntax error but I am not getting it. Please help me in solving this.

#include <stdio.h>
int add(int arr[]);

int main(void)
{
    int nums[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };
    int result = add(nums);
    printf("Result: %d\n", result);
    return 0;
}

int add(int arr[])
{
    int total = 0;
    int i;
    for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
        total += arr[i];
    }
    return total;
}

The error I am facing is this ->
main.c:16:27: warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int *’ [-Wsizeof-array-argument] for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { ^ main.c:12:13: note: declared here int add(int arr[]) ^~~ Result: 3

标签: arrayscfunction

解决方案


推荐阅读