您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何使用指针在C语言中计算数组元素的总和?

2024/11/22 10:55:12发布15次查看
指针是一个存储其他变量地址的变量。
考虑以下语句 -
int qty = 179;
声明指针声明指针的语法如下 -
int *p;
这里,'p'是一个指针变量,它保存其他变量的地址。
指针的初始化地址运算符(&)用于初始化指针变量.
例如,
int qty = 175;int *p;p= &qty;
指针数组它是地址集合(或)指针集合。
声明以下是指针数组的声明 -datatype *pointername [size];
例如,
int *p[5];
it represents an array of pointers that can hold five integer element addresses.
initialization‘&’ is used for initialization
例如,
int a[3] = {10,20,30};int *p[3], i;for (i=0; i<3; i++) (or) for (i=0; i<3,i++)p[i] = &a[i];p[i] = a+i;
accessingindirection operator (*) is used for accessing.
例如,
for (i=0, i<3; i++)printf ("%d", *p[i]);
程序以下是使用指针计算数组元素之和的 c 程序 -
 现场演示
//sum of array elements using pointers#include <stdio.h>#include <malloc.h>void main(){ int i, n, sum = 0; int *ptr; printf("enter size of array :
"); scanf("%d", &n); ptr = (int *) malloc(n * sizeof(int)); printf("enter elements in the list
"); for (i = 0; i < n; i++){ scanf("%d", ptr + i); } //calculate sum of elements for (i = 0; i < n; i++){ sum = sum + *(ptr + i); } printf("sum of all elements in an array is = %d
", sum); return 0;}
输出当执行上述程序时,会产生以下结果 -
enter size of array:5enter elements in the list1213141516sum of all elements in an array is = 70
以上就是如何使用指针在c语言中计算数组元素的总和?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product