Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Câu đố con trỏ C/C++: Kích thước con trỏ

Giới thiệu

Con trỏ lưu địa chỉ của biến khác. Kích thước con trỏ phụ thuộc vào kiến trúc: 4 byte (32-bit), 8 byte (64-bit). Kích thước kiểu dữ liệu trỏ đến không ảnh hưởng đến kích thước con trỏ.

Câu đố

int a = 6;
int *p = &a;
int arr[5][8][3];
int *q = &arr[0][0][0];

// Dự đoán sizeof(p) và sizeof(q)

Giải thích

  • sizeof(p) = kích thước con trỏ = 8 byte (trên 64-bit)
  • sizeof(q) = kích thước con trỏ = 8 byte (không phải kích thước mảng!)
  • sizeof(arr) = 5×8×3×sizeof(int) = 480 byte

Lỗi thường gặp: nhầm sizeof(con trỏ) với sizeof(mảng).

Code C++ minh họa

#include <iostream>
using namespace std;

int main() {
    int a = 6;
    int *p = &a;
    int arr[5][8][3];
    int *q = &arr[0][0][0];
    int ans;

    cout << "the value of a is " << a << endl;
    cout << "predict the size of p (pointer): ";
    cin >> ans;
    if (ans == sizeof(p))
        cout << "Hurry! your prediction is right\n";
    else
        cout << "Your Guess is wrong\n";

    cout << "Now try this\narr is a 3D array\n";
    cout << "predict the size of q (pointer to first element): ";
    cin >> ans;
    if (ans == sizeof(q))
        cout << "Hurry! your prediction is right\n";
    else
        cout << "Your Guess is wrong\n";

    cout << "sizeof(arr) = " << sizeof(arr) << " bytes\n";
    return 0;
}

Kết quả mẫu (64-bit)

the value of a is 6
predict the size of p (pointer): 8
Hurry! your prediction is right
Now try this
arr is a 3D array
predict the size of q (pointer to first element): 8
Hurry! your prediction is right
sizeof(arr) = 480 bytes