简体   繁体   English

“C”为什么我将变量声明为“指针”?

[英]'C' why I declare the variable as 'pointer'?

#include <stdio.h>
void main()
{
int a[] = {10,20,30,40,50,60,70,80,90,100};
int k,m,i,*ptr;
k=m=0;
ptr=a;
for(i=0; i<10; i+=2)
{
    k+=ptr[i];
    m+=ptr[i+1];
}
printf("***** result ***** \n\n");
printf("(10+30+50+70+90)=%d\n",k); //250
printf("(20+40+60+80+100)=%d\n",m); //300
}

Why I use the *ptr as 'pointer'?为什么我使用 *ptr 作为“指针”? I mean it cannot run using just 'ptr'?我的意思是它不能仅使用“ptr”运行?

How the variable '*ptr' load the array 'a[]'.变量 '*ptr' 如何加载数组 'a[]'。

Here the pointer ptr points to the first element of the array.这里指针 ptr 指向数组的第一个元素。 If you declared it as a regular variable, you could only assign one value to it.如果将其声明为常规变量,则只能为其分配一个值。 But now you can assign the address of an array element & access all other elements through it by incrementing or decrementing the value of the pointer, which you won't be able to do, if it was declared as a variable.但是现在您可以通过增加或减少指针的值来分配数组元素的地址并通过它访问所有其他元素,如果它被声明为变量,您将无法这样做。

The pointer ptr points to the first element of the array.指针 ptr 指向数组的第一个元素。 So if you write ptr[1], it points to the second element of the array (since arrays are '0'-indexed).所以如果你写 ptr[1],它指向数组的第二个元素(因为数组是 '0'-indexed)。 You can access other elements too.您也可以访问其他元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM