Ở đây chúng ta sẽ xem cách in biểu diễn bộ nhớ của các biến C. Ở đây, chúng tôi sẽ hiển thị số nguyên, số thực và con trỏ.
Để giải quyết vấn đề này, chúng ta phải làm theo các bước sau -
- Nhận địa chỉ và kích thước của biến
- Nhập địa chỉ vào con trỏ ký tự để nhận địa chỉ byte
- Bây giờ lặp lại kích thước của biến và in giá trị của con trỏ đã đánh máy.
Ví dụ
#include <stdio.h>
typedef unsigned char *byte_pointer; //create byte pointer using char*
void disp_bytes(byte_pointer ptr, int len) {
//this will take byte pointer, and print memory content
int i;
for (i = 0; i < len; i++)
printf(" %.2x", ptr[i]);
printf("\n");
}
void disp_int(int x) {
disp_bytes((byte_pointer) &x, sizeof(int));
}
void disp_float(float x) {
disp_bytes((byte_pointer) &x, sizeof(float));
}
void disp_pointer(void *x) {
disp_bytes((byte_pointer) &x, sizeof(void *));
}
main() {
int i = 5;
float f = 2.0;
int *p = &i;
disp_int(i);
disp_float(f);
disp_pointer(p);
disp_int(i);
} Đầu ra
05 00 00 00 00 00 00 40 3c fe 22 00 00 00 00 00 05 00 00 00