c語言中關於 和 的區別的一點小結

2021-07-14 16:13:08 字數 2315 閱讀 7910

首先先大概明確下&和*的含義

int a;

scanf(「%d」,&a);//取

a的記憶體位址,把鍵盤輸入的整形資料存在

int型變數a中。

printf("%d",&a);//獲取a的位址,並輸出

注:在c++中,&

還有引用的意思。粗淺的說,同一塊記憶體單元有不同的指標

*:定義指標變數,即指向記憶體單元的指標,用來獲取指標指向的變數的值.

int* a;//定義乙個int型指標

b=*a;//獲取*a的所指向的變數的值

必須注意,*和&出現在宣告語句和執行語句中的含義是不同的。

然後通過我們最為數值的資料交換的三個例子來看他們的區別。

#include "stdio.h"

/*引用x和

y的位址,雖然傳遞的是x和

y的值,但函式獲取x和y的位址,改變其位址儲存的資料,但a和

b所指的記憶體塊仍未改變*/

void swap1(int &a,int &b)

int temp=a;

a=b;

b=temp;

printf("%d %d\n",&a,&b);

/*傳遞的是m和

n的位址,更改了m和

n所指記憶體塊的資料*/

void swap2(int* a, int* b)

int temp=*a;

*a=*b;

*b=temp;

printf("%d %d\n",a,b);

/*傳遞的是p和

q的位址,

a指向了p,

b指向了

q,但是經過交換後,

a指向了q,

b指向了p,

p和q所指的記憶體塊的資料並未改變*/

void swap3(int* a, int* b)

printf("%d %d\n",a,b);

int temp=*a;

a=b;

b=&temp;

printf("%d %d\n",a,b);

printf("%d %d\n",*a,*b);

void main()

int x = 1,y = 2;

int m = 3,n = 4;

int p = 5,q = 6;

printf("x=%d y=%d m=%d n=%d p=%d q=%d \n",x,y,m,n,p,q);

printf("交換前

x的位址

%d y

的位址%d\n",&x,&y);

swap1(x,y);

printf("交換後

x的位址

%d y

的位址%d\n",&x,&y);

printf("交換前

m的位址

%d n

的位址%d\n",&m,&n);

swap2(&m,&n);

printf("交換後

m的位址

%d n

的位址%d\n",&m,&n);

printf("交換前

p的位址

%d q

的位址%d\n",&p,&q);

swap3(&p,&q);

printf("交換後

p的位址

%d q

的位址%d\n",&p,&q);

printf("x=%d y=%d m=%d n=%d p=%d q=%d \n",x,y,m,n,p,q);

}執行結果:

x=1 y=2 m=3 n=4 p=5 q=6

交換前x

的位址1638204 y

的位址1638200

1638204 1638200

交換後x

的位址1638204 y

的位址1638200

交換前m

的位址1638196 n

的位址1638192

1638196 1638192

交換後m

的位址1638196 n

的位址1638192

交換前p

的位址1638188 q

的位址1638184

1638188 1638184

1638184 1638088

6 5交換後p

的位址1638188 q

的位址1638184

x=2 y=1 m=4 n=3 p=5 q=6

press any key to continue

無論函式的引數傳遞的是值還是指標,其指標位址的值都未發生改變,改變的只是指標所指的記憶體塊儲存的資料。

關於C語言中open和fopen的一點困惑

最近在深入學習c語言,並且用到了一下檔案操作函式,其中一直讓我不理解的是open和fopen函式到底有啥差別,最近看了一文章,有了一定的了解 open函式原型 int open const char pathname,int flags,mode t mode fopen函式原型 file fope...

C語言中關於巨集定義的一點總結

1 常見的巨集定義語句有不帶引數的巨集定義和帶引數的巨集定義兩種 2 帶引數的巨集定義,在比較複雜時,往往通過 字元進行換行分割,來使其更加清晰。比如 include include define func a,b printf the add of a and b is d n a b int m...

C語言中關於巨集 的使用,注意一點

文章 首先已知 define a hello define b world 如何使用巨集a,b表示出字串 helloworld 答案1 define c a b 答案2 define c a,b a b define c a,b c a,b 答案1驗證 例如使用巨集預編譯案例 include def...