簡體   English   中英

指向結構變量的指針的大小是多少?

[英]What is the sizeof the pointer pointing to a structure variable?

在這兩種情況下,我都試圖打印指針的大小。 對於這兩種情況,我都得到8 16作為 output。

#include <stdio.h>

struct Book
{
    char name[10];
    int price;
};

int main(void)
{
    struct Book a;      // Single structure variable
    struct Book* ptr;   // Pointer of Structure type

    ptr = &a;

    struct Book b[10];  // Array of structure variables
    struct Book* p;     // Pointer of Structure type

    p = &b;

    printf("%ld %ld\n",sizeof(ptr),sizeof(*ptr));
    printf("%ld %ld\n",sizeof(p),sizeof(*p));

    return 0;
}

首先, sizeof運算符產生一個類型size_t ,您必須使用%zu來打印它。

然后,通常在任何體系結構中,指針的大小始終是恆定的,與它們指向的類型無關。 換句話說,一個指針需要保存一個 memory 位置,並且對於任何正常架構,(memory 位置的)地址具有固定大小。 因此,任何指針的大小都是相同的。

這是你想要的,在第二種情況下:

printf("%zu %zu\n", sizeof(p1), sizeof(*p1));
// Output
8 160

好的。 讓我們從頭開始。

正如Sourav Ghosh在他的回答中所說, pointer需要保存 memory 位置,對於任何正常架構,地址(memory 位置)具有固定大小。因此,任何指針的大小都是相同的。” ,無論它指向的數據類型如何。

現在遇到您的問題,考慮並嘗試理解您的程序的這個修改版本:

#include <stdio.h>

struct Book
{
    char name[10];
    int price;
};

int main(void)
{
    struct Book b[10];  // Array of structure variables
    struct Book* p;     // Pointer to type struct Book
    struct Book (*p1)[10]; // Pointer to type struct Book[], which is array of type struct Book

    p = b; // same as p = &b[0] but not as p = &b
    p1 = &b; // this is how assignment of a pointer to array is done

    printf("%zu %zu\n", sizeof(struct Book*), sizeof(struct Book));
    printf("%zu %zu\n",sizeof(p),sizeof(*p));
    printf("%zu %zu\n",sizeof(p1),sizeof(*p1));

    return 0;
}

Output:

// perhaps on your PC
8 16
8 16
8 160
// on my PC
4 16
4 16
4 160

您在 output 中看到sizeof(struct Book), sizeof(p), and sizeof(p1)都是相同的。 因此,任何類型的指針的大小都是相同的。

但是當您打印struct Book的大小時,即您在詢問編譯器, “告訴我這個 struct Book 包含多少 memory 字節”

對於前兩種情況(sizeof(struct Book) or sizeof(*p)) ,它是 16,對於最后一種情況,它是 160,這是struct Book類型的 10 個變量的大小。

如果您想知道為什么16作為stuct Book類型變量的大小,那是因為charint成員之間有2 padding bytes

閱讀這個關於填充和包裝結構的 SO 問題

暫無
暫無

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

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