c指针介绍

本文概述

  • 声明一个指针
  • 指针的优点
  • 指针的用法
  • 地址(
  • 空指针
  • 指针程序, 无需使用3rd变量即可交换两个数字。
  • 读取复杂的指针
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

指针示例
下面给出了使用指针打印地址和值的示例。
c指针介绍

文章图片
如上图所示,指针变量存储数字变量的地址,即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;

c指针介绍

文章图片
指针的优点1)指针减少了代码并提高了性能,它用于检索字符串,树等,并与数组,结构和函数一起使用。
2)我们可以使用指针从一个函数返回多个值。
3)它使你能够访问计算机内存中的任何内存位置。
指针的用法c语言中有许多指针的应用程序。
1)动态内存分配
在C语言中,我们可以使用malloc()和calloc()函数(在使用指针的情况下)动态分配内存。
2)数组,函数和结构
c语言中的指针广泛用于数组,函数和结构中。它减少了代码并提高了性能。
地址(操作员的地址
#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值。它将提供更好的方法。
int *p=NULL;

在大多数库中,指针的值为0(零)。
指针程序,无需使用3rd变量即可交换两个数字。
#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左到右
*, identifier2右到左
Data type3
在这里,我们必须注意到,
  • ():此运算符是用于声明和定义函数的方括号运算符。
  • []:此运算符是数组下标运算符
  • *:此运算符是指针运算符。
  • 标识符:这是指针的名称。优先级将始终分配给它。
  • 数据类型:数据类型是指针要指向的变量的类型。它还包括修饰符,例如signed int,long等。
如何读取指针:int(* p)[10]。
要读取指针,我们必须看到()和[]具有相同的优先级。因此,在这里必须考虑它们的关联性。关联性是从左到右,因此优先级为()。
在方括号()中,指针运算符*和指针名称(标识符)p具有相同的优先级。因此,此处必须考虑它们的关联性,即从右到左,因此优先级为p,第二优先级为*。
由于数据类型具有最后优先级,因此将[]分配第三优先级。因此,指针将如下所示。
  • 字符-> 4
  • * -> 2
  • p-> 1
  • [10] -> 3
将读取该指针,因为p是指向大小为10的整数数组的指针。

如何阅读以下指针?
int (*p)(int (*)[2], int (*)void))

说明
【c指针介绍】该指针将被读取,因为p是指向该函数的指针,该函数接受第一个参数作为指向大小为2的整数的一维数组的指针,第二个参数作为指向该函数的指针,该函数的参数为??void并且返回类型为整数。

    推荐阅读