學點 C 語言(23): 資料類型 – 給指標分配記憶體

來源:互聯網
上載者:User
C 語言的記憶體配置很簡單: malloc、calloc、realloc、free

malloc(位元組數); 返回記憶體段的首地址, void 的.

calloc(個數, 類型大小); 和 malloc 的區別就是它會初始化記憶體為空白.

realloc(原指標, 位元組數); 重新分配由 malloc、calloc 分配的記憶體; 這裡有太多注意事項:
1、如果縮小了, 會截掉一塊, 會保留前面的內容;
2、如果擴大了, 仍會保留已有的內容, 但新加的記憶體不會初始化;
3、在擴大時, 有可能記憶體位址會變化, 這樣原來的指標就廢了, 不過傳回值是新指標, 所以繼續使用的應該是傳回值.

如果分配失敗會返回 NULL, 一般是因為記憶體不足; 分配 0 位元組記憶體也會返回 NULL 但這沒有意義.

它們都是用 free(指標) 釋放.

1. 給一個整數分配記憶體:

#include <stdio.h>#include <stdlib.h>int main(void){    int *p = NULL;//    p = malloc(sizeof(int));  /* 應該像下一句同時類型轉換, 不然在 C++ 裡面不行 */    p = (int *)malloc(sizeof(int));        *p = 100;    printf("%d\n", *p);        free(p);        getchar();    return 0;}

2. 給 3 個整數分配記憶體:

#include <stdio.h>#include <stdlib.h>int main(void){    int *p = NULL;        p = (int *)malloc(sizeof(int)*3);        *p = 111;    *(p+1) = 222;    *(p+2) = 333;    printf("%d,%d,%d\n", *p, *(p+1), *(p+2));    free(p);    getchar();    return 0;}

3. 像數組一樣使用:

#include <stdio.h>#include <stdlib.h>int main(void){    int *p = (int *)malloc(sizeof(int)*3);    p[0] = 111;    p[1] = 222;    p[2] = 333;    printf("%d, %d, %d\n", p[0], p[1], p[2]);    free(p);    getchar();    return 0;}

4. calloc 會同時初始化記憶體, malloc 則不會, 不初始化應該更快些:

#include <stdio.h>#include <stdlib.h>int main(void){    const int num = 10;    // calloc 和 malloc 參數也有點區別    long *p1 = (long *)calloc(num, sizeof(long));  /* 會初始化   */    long *p2 = (long *)malloc(num * sizeof(long)); /* 不會初始化 */    int i;    for (i = 0; i 

5. realloc:

#include <stdio.h>#include <stdlib.h>int main(void){    int num = 10;    int i;        long *p = (long *)malloc(num * sizeof(long));    printf("記憶體位址: %p\n~~~~~~~~\n", p);        for (i = 0; i 

6. 判斷記憶體是否分配成功:

#include <stdio.h>#include <stdlib.h>int main(void){    int *p = (int *)malloc(100);    if (p != NULL) printf("分配成功!\n");    if (p) printf("分配成功!\n");    if (p == NULL) printf("記憶體不足!\n");    if (!p) printf("記憶體不足!\n");    free(p);    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.