指標簡化
顧名思義,指標是一種特殊的變數,用於指向另一個變數/指標。
宣告、為指標賦值、檢索值
宣告一個指標
指標變數透過字首 * 符號宣告。
1 2 3 4
|
//<datatype*> pointervariablename;
int *gunpointer=0;
int* gunpointer=0;
float* fp;
|
現在讓我們宣告一些變數來指向
int ivalue=10;
float fvalue=5.0;
指向目標/指標
1 2 3 4 5
|
gunpointer=ivalue; /*invalid u cant point the gun without knowing where the person is*/
gunpointer=&ivalue;/*valid now u know the address, u can point at the person residing at that address*/
gunpointer=&fvalue;/*invalid wrong gun choice,ur using a toy gun to rob a bank
a pointer can only point to a variable of same type*/
|
開火或解引用指標: (從指標獲取值)
現在,一旦指標指向一個變數,你如何獲取指向位置的值或解引用指標?
只需再次使用 * 標記
1 2
|
int ivalue1=*gunpointer;//fetches the value stored at that location
printf("%d",ivalue1);
|
注意: * 用於兩個地方
1 2
|
int* ip ;// here it means u are declaring a pointer to an integer.
int k=*ip;//or printf(“%d”,*ip); here it means dereferencing or fetching the
|
儲存在指標指向的地址的值。
深入研究:(注意:從這裡開始事情可能會變得非常混亂)
二維指標
它們可以被認為是 指向指標的指標
例如1:指向指標的指標
1 2 3
|
char* str="hi im learning pointers";
char** strp=&str;
printf("%s",*strp);
|
這裡strp充當指向str的指標,而str指向字串“hi im learning pointers”的起始地址
當必須使用按引用傳遞填充陣列時,這個概念非常有用
例如2(複雜)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include<iostream>
#include<conio.h>
void populatearray(int** mainarray,int* count)
{
int a[]={1,2,3,4,5};
//create a single dimension array for storing the values
int* myarray=new int[5];
//assign the values to be stored to the array
for(int i=0;i<5;i++)
{
myarray[i]=a[i];
}
//store the count in the adress pointed by formal parameter
*count=5;
//store the array in the adress pointed by formal parameter
*mainarray=myarray;
}
void main()
{ //the main array where values have to be stored
int* arraymain=0;
//count of elements
int maincount=0;
//pass the adess of pointer to array, adress of counter
populatearray(&arraymain,&maincount);
//check whether pass by reference has worked
printf("The array Elements:\n");
for(int i=0;i<maincount;i++)
{
printf("\n%d",arraymain[i]);
}
getch();
}
|