學點 C 語言(21): 資料類型 – 數組與指標

來源:互聯網
上載者:User
1. 擷取數組的地址無須 &, 因為數組名本身就是個地址
#include <stdio.h>int main(void){    char c = 'A';    char cs[] = "ABC";    printf("%c, %s\n", c, cs);           /* 擷取字元及字元數組的內容 */    printf("%p, %p, %p\n", &c, cs, &cs); /* 擷取字元及字元數組的地址, cs 與 &cs 沒有區別*/    getchar();    return 0;}

2. 數組元素的地址是連續的:

#include <stdio.h>int main(void){    char cs[] = "ABC";    printf("%p\n%p\n%p\n%p\n", cs, &cs[0], &cs[1], &cs[2]);    getchar();    return 0;}

3. 數組名所代表的地址就是第一個元素的地址:

#include <stdio.h>int main(void){    char str[] = "ABC";    char *p1 = str;    char *p2 = &str[0];    printf("%p, %p\n", p1, p2);    getchar();    return 0;}

4. 通過指標訪問數組元素:

#include <stdio.h>int main(void){    char str[] = "ABC";    char *p = str;    printf("%c\n", *p);    printf("%c\n", *p+1);    printf("%c\n", *p+2);    printf("\n");        printf("%c\n", *p);    printf("%c\n", *++p);    printf("%c\n", *++p);    getchar();    return 0;}

5. 通過指標遍曆數組:

#include <stdio.h>int main(void){    char str[] = "123456789";    char *p = str;    int i;    for (i = 0; i 
#include <stdio.h>int main(void){    char str[] = "123456789";    char *p = str;    while (*p != '\0') {        printf("%c\n", *p);        p++;    }    getchar();    return 0;}
#include <stdio.h>#include <string.h>int main(void){    char str[] = "123456789";    char *p = str;    int i;    for (i = 0; i 
#include <stdio.h>int main(void){    int nums[] = {111,222,333,444};    int *p = nums;    int i;    for (i = 0; i 

6. 注意: 指標+1 是根據元素大小移動一個位置

#include <stdio.h>int main(void){    int nums[] = {111,222,333,444};    int *p = nums;    int i;    printf("%d\n", *p);    printf("%d\n", *(p+1));    printf("%d\n", *p+1);  /* 不是這樣; 這是代表取值後再 + 1 */        getchar();    return 0;}

7. 上面的指標其實都是數組元素的指標, 如何聲明真正的數組指標呢?

#include <stdio.h>int main(void){    int nums[4] = {111,222,333,444};    int (*p)[4] = &nums;      /* 注意其中的小括弧 */    printf("%d\n", (*p)[1]);  /* 用起來並不方便   */    printf("%d\n", (*p)[2]);        getchar();    return 0;}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.