首页 > 文章列表 > 在C语言中使用指针算术来计算数组的总和

在C语言中使用指针算术来计算数组的总和

指针 总和 算术
261 2023-09-05

在这个程序中,我们需要使用指针运算来求数组元素的和。

这里我们使用 * 来表示存储在内存地址处的值,并且该地址将保留存储在变量中。因此“int *ptr”表示ptr是一个变量,其中包含一个地址,该地址的内容是一个整数。

*p表示它是一个指针变量。使用它和 sum() 我们将找出数组元素的总和。

示例代码

#include <stdio.h>
void s(int* a, int len{
   int i, s_of_arr = 0;
   for (= 0; i < len; i++)
      s_of_arr = s_of_arr + *(+ i);
   printf( "sum of array is = %d" ,s_of_arr);
}
int main() {
   int arr[] = { 1,2,4,6,7,-5,-3 };
   s(arr, 7);
   return 0;
}

输出

Sum of array = 12

算法

Begin
   Initialize array to hold the variables.
   Call function s to get the sum of the variables.
   Print the sum.
End.