我試圖將一個數組傳遞給一個函數,該函數總結了數組中的所有元素,但是在行sum+=a[i];
處遇到訪問錯誤我解決這個問題?這裏是代碼:線程1:EXC_BAD_ACCESS(代碼= 1,地址= 0x7fff00000001)
#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;
}
@Josh - 你爲什麼要拉''objective-c'標籤來支持'C'?這顯然是'objective-c'代碼 – Mike 2013-03-11 19:31:00
不是,@Mike - 問題本身完全基於C的內存管理。唯一需要ObjC運行時的是'@ autoreleasepool',由於沒有放入ObjC對象,因此它並沒有做任何事情。它必須被編譯爲ObjC,因爲它使用了'NSString',但這些與實際問題或解決方案沒有關係。這兩件事都可以在不影響這段代碼的可編譯性的情況下被移除,問題將會是一樣的,並且正好在C的域中。 – 2013-03-11 19:38:32