首頁 >後端開發 >C++ >編寫一個C程序,示範指標的範例

編寫一個C程序,示範指標的範例

WBOY
WBOY轉載
2023-09-21 19:33:021030瀏覽

指標是一個儲存另一個變數位址的變數。

指標的特性

  • 指標節省記憶體空間。

  • 由於直接存取記憶體位置,指標的執行時間更快。

  • 在指標的幫助下,記憶體被有效地訪問,即動態分配和釋放記憶體。

  • 指標與資料結構一起使用。

宣告一個指標

int *p;

這表示「p」是一個指標變量,它保存另一個整數變數的位址。

指標的初始化

位址運算子(&)用於初始化指標變數。

例如,

int qty = 175;
int *p;
p= &qty;

編寫一個C程序,示範指標的範例

透過變數存取變數指標

要存取變數的值,請使用間接運算子 (*)。

程式

 現場示範

#include<stdio.h>
void main(){
   //Declaring variables and pointer//
   int a=2;
   int *p;
   //Declaring relation between variable and pointer//
   p=&a;
   //Printing required example statements//
   printf("Size of the integer is %d</p><p>",sizeof (int));//4//
   printf("Address of %d is %d</p><p>",a,p);//Address value//
   printf("Value of %d is %d</p><p>",a,*p);//2//
   printf("Value of next address location of %d is %d</p><p>",a,*(p+1));//Garbage value from (p+1) address//
   printf("Address of next address location of %d is %d</p><p>",a,(p+1));//Address value +4//
   //Typecasting the pointer//
   //Initializing and declaring character data type//
   //a=2 = 00000000 00000000 00000000 00000010//
   char *p0;
   p0=(char*)p;
   //Printing required statements//
   printf("Size of the character is %d</p><p>",sizeof(char));//1//
   printf("Address of %d is %d</p><p>",a,p0);//Address Value(p)//
   printf("Value of %d is %d</p><p>",a,*p0);//First byte of value a - 2//
   printf("Value of next address location of %d is %d</p><p>",a,*(p0+1));//Second byte of value a - 0//
   printf("Address of next address location of %d is %d</p><p>",a,(p0+1));//Address value(p)+1//
}

輸出

Size of the integer is 4
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 10818512
Address of next address location of 2 is 6422032
Size of the character is 1
Address of 2 is 6422028
Value of 2 is 2
Value of next address location of 2 is 0
Address of next address location of 2 is 6422029

以上是編寫一個C程序,示範指標的範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除