[英]C : function that calculates the sum of an array using pointers
the purpose is to return the sum of *a into *sum but I am not very good with pointers, I believe there should be a & somewhere目的是将 *a 的总和返回到 *sum 但我对指针不是很好,我相信某处应该有 &
int sumArray (int * a, int len , int * sum ){
if (a==NULL || sum==NULL ) return -1;
int i;
for (i=0;i<len;i++){
sum[i]+=a[i];
}
return 0;
}
From what I understand from your comment, the parameter sum is not an array, but rather the variable where the sum will be stored.根据我从您的评论中了解到的情况,参数 sum 不是数组,而是存储总和的变量。 And since sum is a pointer, to store values into it, you must access its value this way: (*sum)
由于 sum 是一个指针,要将值存储到其中,您必须以这种方式访问它的值: (*sum)
int sumArray (int * a, int len , int * sum ){
if (a==NULL || sum==NULL ) return -1;
int i;
(*sum) = 0 ;
for (i=0;i<len;i++){
(*sum) += a[i];
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.