地址運算符:&

本文內容來自《C Prime Plus(第五版)中文版》第233頁。


C中最重要的(有時也是最複雜的)概念之一就是指針(pointer),也就是用來存儲地址的變量。一元運算符&可以取得變量的存儲地址。假設pooh是一個變量的名字,那麼&pooh就是該變量的地址。一個變量的地址可以被看做是改變量在內存中的位置。假定使用了以下語句:

pooh=24;

並且假定pooh的存儲位置是0B76(PC的地址一般以3位十六進制數的形式表示)。那麼語句:

printf("%d%p\n",pooh,&pooh);

將輸出如下數值(%p是輸出地址的說明符):

240876

看下面例子:

/* loccheck.c  -- checks to see where variables are stored  */
#include <stdio.h>
void mikado(int);                      /* declare function  */
int main(void)
{
    int pooh = 2, bah = 5;             /* local to main()   */

    printf("In main(), pooh = %d and &pooh = %p\n",
            pooh, &pooh);
    printf("In main(), bah = %d and &bah = %p\n",
            bah, &bah);
    mikado(pooh);
    
    return 0;
}

void mikado(int bah)                   /* define function   */
{
    int pooh = 10;                     /* local to mikado() */

    printf("In mikado(), pooh = %d and &pooh = %p\n",
            pooh, &pooh);
    printf("In mikado(), bah = %d and &bah = %p\n",
            bah, &bah);
}

其輸出結果如下:


In mian(),pooh=2 and %pooh=0x0012ff48

In mian(),bah=5 and %bah=0x0012ff44

In mian(),pooh=10 and %pooh=0x0012ff34

In mian(),bah=2 and% bah=0x0012ff40


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章