So I have a simple C program that calculates the sum of elements in an array. The problem, as it appears to me, is the notation int[] arr
. Apparently, the correct notation expected is int arr[]
. On running my program with the first notation, I got some eight errors. When none of the errors made sense to me, I just used the second array notation, and it worked.
Here's the code-
#include <stdio.h>
int sumOfArray(int[], int);
int main()
{
int[] A={1,2,3,4,5};
int sum=0;
int size=sizeof(A)/sizeof(A[0]);
sum=sumOfArray(A,size);
printf("\n The sum of the array is: %d\n", sum);
return 0;
}
int sumOfArray(int[] arr, int n)
{
int sum=0,x;
for (x=0; x<n; x++) {
sum+=arr[x];
}
return sum;
}
If it helps, here are the errors generated:
p6.c:15:8: error: expected identifier or '('
int[] A={1,2,3,4,5};
^
p6.c:17:21: error: use of undeclared identifier 'A'
int size=sizeof(A)/sizeof(A[0]);
^
p6.c:17:31: error: use of undeclared identifier 'A'
int size=sizeof(A)/sizeof(A[0]);
^
p6.c:18:20: error: use of undeclared identifier 'A'
sum=sumOfArray(A,size);
^
p6.c:23:22: error: expected ')'
int sumOfArray(int[] arr, int n)
^
p6.c:23:15: note: to match this '('
int sumOfArray(int[] arr, int n)
^
p6.c:23:5: error: conflicting types for 'sumOfArray'
int sumOfArray(int[] arr, int n)
^
p6.c:11:5: note: previous declaration is here
int sumOfArray(int[], int);
^
p6.c:23:19: error: parameter name omitted
int sumOfArray(int[] arr, int n)
^
p6.c:26:17: error: use of undeclared identifier 'n'
for (x=0; x<n; x++) {
^
p6.c:27:14: error: use of undeclared identifier 'arr'
sum+=arr[x];
^
I was under the impression that both array notations are acceptable. In fact, int[] arr
is advised in many cases. But then what went wrong here? Any suggestions?
Many thanks!