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.

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);
}

Put the code tags!

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.