C语言入门经典——基础知识(指针 数组 多维数组)
|
****************************************指針***************************************
******************************能夠存儲地址的變量稱為指針*****************************
指針的聲明:
? ? int *pointer = NULL; ? 或者 ?int *pointer = 0;
? ? 測試指針是否為空:if(!pointer) ?或者 ?if(pointer != NULL)
? ? 聲明一個指向int類型變量的指針,pointer變量的類型是 Int *,它可以存儲任意Int類型變量的地址。
? ? NULL是標準庫中定義的一個常量,對于指針它表示0。NULL是一個不指向任何內(nèi)存位置的值。這表示,使用不指向任何對象的指針,不會意外覆蓋內(nèi)存。
? ? 我們知道變量pointer是一個指針是不夠的,更重要的是,編譯器必須知道它所值的變量的類型。沒有這個信息,根本不可能知道它占用多少內(nèi)存,或者如何處理它所指的內(nèi)存的內(nèi)容。
??? int? number = 10; ? ? int *pointer =? &number; ? ? 第一條語句會分配一塊內(nèi)存來存儲一個整數(shù),使用number名稱可以訪問這個整數(shù)。 ? ??pointer的初值是number變量的地址。兩句的順序不能顛倒,編譯器要先分配空間,才能使用number的地址初始化pointer變量。 ? ? number 和 pointer 的地址是變量在這臺計算機上存放的地方。 ? ? number變量是一個整數(shù)(10),但是pnumber變量是number的地址。 ? ? 使用*pnumber可以訪問number的值,即間接地使用number變量的值。 |
??指針的使用:(說明:使用一個指針變量可以改變其它許多變量的值,但是變量的類型要相同)
#include<stdio.h> int main() {long num1 = 0L;long num2 = 0L;long *pnum = NULL;pnum = &num1; //get address of num1*pnum = 2; //set num1 to 2++num2; //increment num2printf("num1=%ld num2=%ld\n",num1,num2);// 2 1num2 += *pnum; //add num1 to num2printf("num1=%ld num2=%ld\n",num1,num2);//2 3//指針重新指向了 num2pnum = &num2; //get addres of num2l++*pnum;//increment number2 indirectly //(++*pnum遞增了pnum指向的值 == (*pnum)++ ) //如果省略括號,就會遞增pnum所含的地址,printf("num1=%ld num2=%ld\n",num1,num2);//2 4printf("\nnum1=%ld num2=%ld *pnum=%ld *pnum+num2=%ld\n",num1,num2,*pnum,*pnum+num2);//2 4 4 8return 0; }指針與常量:
? ? 指向常量的指針:
????? ? 可以改變指針中存儲的地址,但是不允許使用指針改變它指向的值。
? ? 常量指針:
????? ? 指針中存儲的地址不能改變,但是可以使用指針改變它指向的值。
int count = 43;int *const pcount = &count;printf("==%d\n",*pcount); //43int item = 34; // pcount = &item;//error: assignment of read-only variable ‘pcount’*pcount = 345;//通過指針引用了存儲在const中的值,將其改為345printf("==%d\n",*pcount);//345?指向常量的常指針:
????? ? 指針中存儲的地址不能改變,指針指向的值也不能被改變。
int itemm = 25;const int *const pitem = &item;****************************************數(shù)組***************************************
**********************************相同類型的對象集合*********************************
? ?//數(shù)組與指針的區(qū)別是:可以改變指針包含的地址,但是不能改變數(shù)組名稱引用的地址
//數(shù)組名稱本身引用了一個地址char multiple[] = "My string";char *p = &multiple[0];printf("The address of the first arry element:%p\n",p);//The address of the first arry element:0x7ffddba45350 p = multiple;printf("The address obtained from the array name:%p\n",p);//The address obtained from the array?name:0x7ffddba45350//多維數(shù)組
address of board[0][0] : 0x7ffee67e6f50
value of *board[0]: 1
address of board[0]: 0x7ffee67e6f50
value of **board : 1
address of board : 0x7ffee67e6f50
board:1? ? ? ? ? ? ? ? ?board:2? ? ? ? ? ? ? ? ? ?board:3? ? ? ? ? ? ? ? board:4? ? ? ? ? ? ? board:5
board:6? ? ? ? ? ? ? ? ?board:7? ? ? ? ? ? ? ? ? ?board:8? ? ? ? ? ? ? ??board:9
總結(jié)
以上是生活随笔為你收集整理的C语言入门经典——基础知识(指针 数组 多维数组)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言入门经典——基础知识(数据类型)(
- 下一篇: 函数 —— strncpy() (内存重