C语言入门经典——基础知识(指针 数组 多维数组)
|
****************************************指针***************************************
******************************能够存储地址的变量称为指针*****************************
指针的声明:
int *pointer = NULL; 或者 int *pointer = 0;
测试指针是否为空:if(!pointer) 或者 if(pointer != NULL)
声明一个指向int类型变量的指针,pointer变量的类型是 Int *,它可以存储任意Int类型变量的地址。
NULL是标准库中定义的一个常量,对于指针它表示0。NULL是一个不指向任何内存位置的值。这表示,使用不指向任何对象的指针,不会意外覆盖内存。
我们知道变量pointer是一个指针是不够的,更重要的是,编译器必须知道它所值的变量的类型。没有这个信息,根本不可能知道它占用多少内存,或者如何处理它所指的内存的内容。
int number = 10; int *pointer = &number; 第一条语句会分配一块内存来存储一个整数,使用number名称可以访问这个整数。 pointer的初值是number变量的地址。两句的顺序不能颠倒,编译器要先分配空间,才能使用number的地址初始化pointer变量。 number 和 pointer 的地址是变量在这台计算机上存放的地方。 number变量是一个整数(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;****************************************数组***************************************
**********************************相同类型的对象集合*********************************
//数组与指针的区别是:可以改变指针包含的地址,但是不能改变数组名称引用的地址
//数组名称本身引用了一个地址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//多维数组
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
总结
以上是生活随笔为你收集整理的C语言入门经典——基础知识(指针 数组 多维数组)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: C语言入门经典——基础知识(数据类型)(
- 下一篇: 函数 —— strncpy() (内存重