指针是一个存储其他变量地址的变量。
考虑以下语句 -
int qty = 179;

声明指针的语法如下 -
int *p;
这里,'p'是一个指针变量,它保存其他变量的地址。
立即学习“C语言免费学习笔记(深入)”;
地址运算符(&)用于初始化指针变量.
例如,
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.
‘&’ 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;Indirection 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 : </p><p>");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int));
printf("Enter elements in the List </p><p>");
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</p><p>", sum);
return 0;
}当执行上述程序时,会产生以下结果 -
Enter size of array: 5 Enter elements in the List 12 13 14 15 16 Sum of all elements in an array is = 70
以上就是如何使用指针在C语言中计算数组元素的总和?的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号