解释 C 语言中指针访问的概念
cserver side programmingprogramming更新于 2024/11/23 1:48:00
指针是一个存储其他变量地址的变量。
指针声明、初始化和访问
考虑以下语句 −
int qty = 179;
声明指针
int *p;
‘p’是一个指针变量,它保存另一个整数变量的地址。
指针的初始化
地址运算符 (&) 用于初始化指针变量。
int qty = 175; int *p; p= &qty;
让我们考虑一个例子,看看指针在访问字符串数组中的元素时是如何有用的。
在这个程序中,我们试图访问存在于特定位置的元素。可以使用操作找到该位置。
通过将预递增指针添加到预递增指针字符串并减去 32,您可以获得该位置的值。
示例
#include<stdio.h> int main(){ char s[] = {'a', 'b', 'c', '
', 'c', '\0'}; char *p, *str, *str1; p = &s[3]; str = p; str1 = s; printf("%d", ++*p + ++*str1-32); return 0; }
输出
77
解释
p = &s[3]. i.e p = address of '
'; str = p; i.e str = address of p; str1 = s; str1 = address of 'a'; printf ("%d", ++*p + ++*str1 - 32); i.e printf("%d", ++
+ a -32); i.e printf("%d", 12 + 97 -32); i.e printf("%d", 12 + 65); i.e printf("%d", 77); Thus 77 is outputted