int a[10],sum,*p;
sum=0;
for(p=&a[0];p<&a[10];p++)
    sum += *p;
printf("%d",sum)

Hi I'm new in turbo c, especially in pointers. Can someone please explain to me how the pointer was used in this program. Thank you in advance.

I know how the program works, but what I cannot understand is why did the program used a pointer and the '&' sign. Thanks.

有帮助吗?

解决方案

This is an illustrative example of Pointers in C, However this code can also be written without using pointers. Here

p=&a[0]

^ stores the memory address of the First value of the array a. And the For loop will execute till the Pointer stores the memory address of the last Array value i.e. a[10].

sum += *p;

^ in the above statement *p stands for the value of the memory address to which pointer p points to. For Example p currently points to a[0]. Then the Value of a[0] will be added to sum. In the next iteration of the For loop, the value of p increases and it will point to a[1].

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top