我正在尝试将一个数组传递给一个函数,该函数总结了数组中的所有元素,但是我在该行遇到了一个错误的访问错误sum+=a[i];
我该如何解决这个问题?这是代码:
#import <Foundation/Foundation.h>
int sum(int*, int);
int main() {
@autoreleasepool {
int size = 0;
int a[size];
int x;
NSLog(@"Enter a size for the array ");
scanf("%i", &size);
NSLog(@"Enter %i numbers to populate the array ", size);
for (int i = 0; i < size; i++) {
scanf("%i", &a[i]);
}
x = sum(a, size);
NSLog(@"The sum of the array is %i ", x);
}
return 0;
}
int sum(int *a, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
return sum;
}