所以我有这个代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,它输出:
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
Run Code Online (Sandbox Code Playgroud)
为什么输出奇怪的数字有时候和正确的答案其他时间?我究竟做错了什么?谢谢你的帮助.
Oli*_*rth 14
在arraySum(),您将混淆何时a用作指针,何时取消引用它以获取它指向的内容.在计算循环限制等时,您希望使用指针本身:
int arraySum(int *a, int n){
int sum = 0;
int *arrayEnd = a + n;
for ( ; a < arrayEnd; a++)
sum += *a;
return sum;
}
Run Code Online (Sandbox Code Playgroud)