1,105,225 Community Members

convert void* to string

Member Avatar
hoke
Newbie Poster
3 posts since Sep 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hullo.
I would be very nearly eternally grateful if someone would explain how to convert a void pointer's target (eg 0xda9f000) into a string in C. Both my own brain and google have failed me on this one. I can do this in printf using the wonderfully inelegant line:
printf("Value:'%p' ", *((unsigned int *)point));
But I want to save the result to a char array.
I have tried:
sprintf(buffer, "%p", *((unsigned int *)point));
But that writes the address in/of $point to $buffer rather than the value that $point is pointing at.

Thanks in advance. I hope my query makes sense.

Nevermind. The sprintf line was working, just I was formatting the output in the wrong way to give myself a misleading impression. Sorry if I wasted anyone's time.

Member Avatar
__avd
Posting Genius (adatapost)
6,703 posts since Oct 2008
Reputation Points: 1,811 [?]
Q&As Helped to Solve: 1,272 [?]
Skill Endorsements: 61 [?]
Moderator
 
0
 

void pointers

A void pointer seems to be of limited, if any, use. However, when combined with the ability to cast such a pointer to another type, they turn out to be quite useful and flexible.

#include <stdio.h>

void use_int(void *);
void use_float(void *);
void greeting(void (*)(void *), void *);

int main(void) {
  char ans;
  int i_age = 22;
  float f_age = 22.0;
  void *p;
  printf("Use int (i) or float (f)? ");
  scanf("%c", &ans);
  if (ans == 'i') {
      p = &i_age;
      greeting(use_int, p);
  }
  else {
     p = &f_age;
     greeting(use_float, p);
  }
   return 0;
}

void greeting(void (*fp)(void *), void *q) {
     fp(q);
}

void use_int(void *r) {
   int a;
   a = * (int *) r;
   printf("As an integer, you are %d years old.\n", a);
}

void use_float(void *s) {
   float *b;
   b = (float *) s;
   printf("As a float, you are %f years old.\n", *b);
}
Member Avatar
Nathan Campos
Junior Poster
189 posts since Jul 2009
Reputation Points: 23 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

Put the code tags!

Thanks!

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article