简体   繁体   English

在 C 中打印出一个字节的值及其地址

[英]Printing out the value of a byte and its address in C

I'm working on pointers right now and I'm trying to get an understanding for how things look in memory so I'm attempting to build this program.我现在正在研究指针,我试图了解内存中的情况,所以我正在尝试构建这个程序。 The goal of it is to take an integer, print its address in memory and then its integer value at each byte.它的目标是取一个整数,在内存中打印它的地址,然后在每个字节打印它的整数值。 So for an integer 4 pairs of (address, value).所以对于整数 4 对 (address, value)。 However, the result of my work is rather confusing as I'm getting strange results such as this.然而,我的工作结果相当令人困惑,因为我得到了这样的奇怪结果。 If someone could explain what I'm doing wrong that would be much appreciated.如果有人能解释我做错了什么,那将不胜感激。 For context, I understand a little bit about computer architecture and memory from a class就上下文而言,我从一门课中了解了一些计算机体系结构和内存

Enter an integer: 287输入一个整数:287

0x7ffd455a7474 31 0x7ffd455a7474 31

0x7ffd455a7475 1 0x7ffd455a7475 1

0x7ffd455a7476 0 0x7ffd455a7476 0

0x7ffd455a7477 0 0x7ffd455a7477 0

#include <stdio.h>

void byte_value(int *);
int main(){

    int n =1;
    printf("Enter an integer: ");

    if (scanf("%d", &n) == 1)

        byte_value(&n);

    

    return 0;  

}

void byte_value(int *p) {
    char *p2=((char *)p);
    char *max=p2+sizeof(int);
    for(;p2<max;p2++){
            printf("%p %u\n",p2,*p2);
    }

    return;

}

I think this version may explain a bit more.我认为这个版本可能会解释更多。 (Hex values are very convenient) (十六进制值非常方便)

void byte_value(void *, size_t);
int main(void)
{

    int n =1;
    printf("Enter an integer: ");

    if (scanf("%d", &n) == 1)
        printf("\n------------\nentered: %d (0x%x)\n", n, (unsigned)n);
        
        byte_value(&n, sizeof(n));
}

void byte_value(void *ptr, size_t size) 
{
    unsigned char *p = ptr;
    while(size--)
    {
        printf("%p - %03u (0x%02x)\n", (void *)p, *p, *p);
        p++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM