gpt4 book ai didi

c - 在c中使用指针的数组总和

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:00 25 4
gpt4 key购买 nike

使用以下代码使用指针查找数组元素的总和。我不知道为什么程序没有在数组末尾结束!!

#include <stdio.h>

#define LEN(a) (int) (sizeof(a)/sizeof(a[0]))

int sum_array(int * , int);

int main(void){

int a[] = {1,2,3,4,5,6,7,8,9};

printf("Array length %d\n",LEN(a));

int sum = sum_array(a,LEN(a));

printf("Sum of array is %d\n",sum);
return 0;
}
int sum_array( int * p , int n){

int sum = 0;

while ( p < p+n ){
printf("Sum of array is %d\n",sum);
sum += *p++;
}

return sum;
}
`

解决了伙计们谢谢!!

int sum_array( int * a , int n){
int sum = 0, *p=a;
while ( p < a+n ){
printf("Sum of array is %d\n",sum);
sum += *p++;
}
return sum;


获取地址边界错误!!

最佳答案

如何p < p + n对于非负值永远为 1 n

你需要存储p的初始值如果您想以这种方式绑定(bind)循环。

为了轻松的生活使用for (int i = 0; i < n; ++i)代替 while (p < p + n)并且,如果你必须并且反对任何专业建议,一旦你掌握了正确的基础知识,就可以采用华而不实的版本。

关于c - 在c中使用指针的数组总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57925561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com