我有这段代码:
#include <stdio.h>
int arraySum (int *a, int n);
int main(void){
int values[3] = {1, 2, 3};
printf("The sum is %i\n", arraySum(values, 3));
return 0;
}
int arraySum(int *a, int n){
int sum = 0;
int arrayEnd = *a + n;
for ( ; *a < arrayEnd; *a++)
sum += *a;
return sum;
}
由于某些原因,它输出了这个:
roman@lmde64 ~/Dropbox/Practice $ gcc practice.c
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -421028781
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -362865581
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -1046881197
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is 6
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is 6
有时输出结果是奇怪的数字,有时则是正确答案。我做错了什么吗?感谢任何帮助。
for(int arrayIndex = 0; arrayIndex < n; arrayIndex++) { sum += a[arrayIndex]; }
。 - Dancrumb