指针简化
顾名思义,指针是一种特殊的变量,用于指向另一个变量/指针。
声明、为指针赋值、检索值
声明一个指针
指针变量通过前缀 * 符号声明。
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();
}
|