About Pointer in C
Pointer, as one of the most powerful tools in C. There are two most obvious advantages of pointer is fast and convenient. Variable in program need a area has a relative address in the RAM in which stores values. Pointer variable is a new variable that stores the address. We can regard that pointer is just the address. I just say something about those two advantages below.
First, define a integer variable number. If we want to store 5 in number, we can write
Written:
There, We have seen how pointer variable works. Perhaps you are puzzled that the lines in program used pointer is more than the first one. So I bring another example next.
Define a array with 10 elements and store 10 value in each element.
Written in normal way:
Written with pointer:
First, define a integer variable number. If we want to store 5 in number, we can write
int number; scanf("%d",&number);Now, let's see how computer works.
- Allocating a area while giving a address for number.
- Transforming number to the address in RAM given before.
- Storing 5 into the address.
Written:
int number; int *pnumber; pnumber=&number; scanf("%d",pnumber);In this code, we set a additional pointer variable pnumber and store the address of variable number in it. Now, pnumber holds a address pointing to number. Value is stored into the address directly without a converting.
There, We have seen how pointer variable works. Perhaps you are puzzled that the lines in program used pointer is more than the first one. So I bring another example next.
Define a array with 10 elements and store 10 value in each element.
Written in normal way:
int array[10],i=0; for(;i<10;i++) scanf("%d",&array[i]);It's easy to know that we store 10 value with 10 times converting.
Written with pointer:
int array[10],i=0; int *parray=array; for(;i<10;i++,parray++) scanf("%d",parray);The array name is his address as well. So, make the pointer point to array when defining a pointer variable parray. As we all know, value is stored straightway without converting a integer variable to a address. Obviously, it's faster because there is no converting.
评论