簡體   English   中英

如果我只為單個 int 分配 4 個字節,那么指針如何存儲第二個 int?

[英]If I allocate only 4 bytes for single int, how then pointer can store second int?

正如我在一個網站上發現的以下代碼:

#include <stdio.h>   
#include <stdlib.h> 

int main(void) 
{
    int *p1 = malloc(4*sizeof(int));  // allocates enough for an array of 4 int
    int *p2 = malloc(sizeof(int[4])); // same, naming the type directly
    int *p3 = malloc(4*sizeof *p3);   // same, without repeating the type name

    if(p1) {
        for(int n=0; n<4; ++n) // populate the array
            p1[n] = n*n;
        for(int n=0; n<4; ++n) // print it back out
            printf("p1[%d] == %d\n", n, p1[n]);
    }

    free(p1);
    free(p2);
    free(p3);
}

輸出:

p1[0] == 0

p1[1] == 1

p1[2] == 4

p1[3] == 9

現在按照上面的代碼我做了這個:

#include <stdio.h>
#include <stdlib.h>
#include "Header.h"

int main()

{

    int  *ip = (int*)malloc(1 * sizeof(int));

    ip[0] = 2;
    ip[1] = 9;

    printf("%d %d",ip[0],ip[1]);



    return 0;
}

輸出:2 9

那么當我只為單個 int 分配字節時,我的指針 *ip 如何存儲多個 int 呢?

您正在寫入超出數組范圍的內存。 遺憾的是,沒有對此進行編譯器檢查,但它有時有效。

注意:這是未定義的行為,不應在任何情況下使用。

請記住, ip[1]等價於*(ip + 1) ,它在語法上對任何指針都有效,即使ip指向單個int而不是int數組。

取消引用或寫入ip[1]未定義的行為 嘗試在第二個程序中的return 0之前添加free(ip)並觀察行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM