How to print a pointer address without printf

后端 未结 4 2086
面向向阳花
面向向阳花 2021-01-07 00:30

I\'m doing an exercise in which I need to print the memory (address) of a pointer. It would be easy to do it with printf(\"%p\", ..) but I\'m not allowed to use

4条回答
  •  执念已碎
    2021-01-07 00:57

    You can try like:

    #include 
    
    void print_memory(const void *addr, size_t size)
    {
        size_t printed = 0;
        size_t i;
        const unsigned char* pc = addr;
        for (i=0; i> 4) & 0xf;
            g += g >= 10 ? 'a'-10 : '0';
            putchar(g);
            printed++;
    
            g = *(pc+i) & 0xf;
            g += g >= 10 ? 'a'-10 : '0';
            putchar(g);
            printed++;
            if (printed % 32 == 0) putchar('\n');
            else if (printed % 4 == 0) putchar(' ');
        }
    }
    
    int main(void) {
    int tab[10] = {0, 23, 150, 255, 12, 16, 21, 42};
    
    print_memory(tab, sizeof(tab)); return (0);
    
        return 0;
    }
    

    Output

    0000 0000 1700 0000 9600 0000 ff00 0000 
    0c00 0000 1000 0000 1500 0000 2a00 0000 
    0000 0000 0000 0000 
    

提交回复
热议问题