C语言指针
C语言中的指针是一个变量,用于存储另一个变量的地址。该变量的类型可以是int,char,数组,函数或任何其他指针。指针的大小取决于体系结构。但是,在32位体系结构中,指针的大小为2个字节。
请考虑以下示例,以定义一个存储整数地址的指针。
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
声明指针
可以使用*(星号)声明c语言中的指针。也称为间接指针,用于取消对指针的引用。
int *a;//pointer to int
char *c;//pointer to char
指针示例
下面给出了使用指针打印地址和值的示例。
如上图所示,指针变量存储数字变量的地址,即fff4、数字变量的值为50。但是指针变量p的地址为aaa3、
借助*(间接操作符),我们可以打印指针变量的值p。
让我们看一下上图所解释的指针示例。
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
输出
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
指向数组的指针
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.
指向函数的指针
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a function
指向结构的指针
struct st {
int i;
float f;
}ref;
struct st *p = &ref;
指针的优点
1)指针减少了指针代码和提高性能,它用于检索字符串,树等,并与数组,结构和函数一起使用。
2)我们可以使用指针从功能中返回多个值。
3)它使您能够访问计算机内存中的任何内存位置。
指针的使用
使用c语言的指针有很多应用。
1)动态内存分配
在c语言中,我们可以在使用指针的地方使用malloc()和calloc()函数动态分配内存。
2)数组,函数和结构
c语言中的指针广泛用于数组,函数和结构中。
(&)运算符的地址
运算符'&'的地址返回变量的地址。但是,我们需要使用%u来显示变量的地址。
#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
输出
value of number is 50, address of number is fff4
NULL指针
未分配任何值但为NULL的指针称为NULL指针。如果声明时在指针中没有指定任何地址,则可以分配NULL值。它将提供更好的方法。
在大多数库中,指针的值为0(零)。
指针程序无需使用第3个变量即可交换两个数字。
#include<stdio.h>
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
return 0;
}
输出
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10
读取复杂的指针
在C语言中读取复杂的指针时,必须考虑几件事。让我们看看所使用的运算符的优先级和关联性关于指针。
操作符 |
优先级 |
关联性 |
(),[] |
1 |
从左到右 |
*,标识符 |
2 |
从右向左 |
数据类型 |
3 |
- |
在这里,我们必须注意
(): 此运算符是用于声明和定义函数的方括号运算符。
[]: 此运算符是数组下标运算符
*: 此运算符是指针运算符。
标识符: 这是指针的名称。优先级将始终分配给它。
数据类型: 数据类型是指针要指向的变量的类型。它还包括修饰符,例如signed int,long等。
如何读取指针: int(* p)[10]。
要读取指针,我们必须看到()和[]具有相同的优先级。因此,在这里必须考虑它们的关联性。关联性从左到右,因此优先级为()。
在方括号()中,指针运算符*和指针名称(标识符)p具有相同的优先级。因此,在这里必须考虑它们的关联性,即从右到左,因此优先级为p,第二优先级为*。
将第三个优先级分配给[],因为数据类型具有最后一个优先。因此,指针将如下所示。
char-> 4
*-> 2
p-> 1
[10]-> 3
将读取该指针,因为p是指向大小为10的整数数组的指针。
示例
如何阅读以下指针?
int (*p)(int (*)[2], int (*)void))
解释
将读取此指针,因为p是指向该函数的指针,该函数接受第一个参数作为指向大小为2的一维整数数组的指针。第二个参数是指向函数的指针,该函数的参数为void,返回类型为整数。