How to print a pointer address without printf

后端 未结 4 2084
面向向阳花
面向向阳花 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 01:12

    You could do something like this... You said printf() is off limits, but you said nothing about sprintf.

     print_bytes(char *ptr, int count)
     {
       int i;
       char string[1024];
       string[0] = 0;
       for(i = 0; i < count; i++)
       {
         sprintf(string,"%s %2x", string, *(ptr+i));
       }
       puts(string);
     }
    

    This should loop through count bytes printing out each hexadecimal byte starting from the passed in address in ptr.

    Obviously, this makes no attempt to properly size the string array. That should be dynamically sized based on the passed in count.

    To substitute write() for puts(), you could use:

     write(1, string, strlen(string)); /* 1 = STDOUT */
    

提交回复
热议问题