解釋C語言中指標訪問的概念
指標是一個變數,它儲存著其他變數的地址。
指標宣告、初始化和訪問
考慮以下語句 −
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
廣告