cfunctionpointers

How to pass pointer of unknown type to function?


I want to pass a variable by value (I used pointers only to avoid giving the parameter a type) into a function so that it can be used by another function contained within. The inner function can be given a variable of any type.

I have already tried using a generic pointer (void*) but it tells me that "'void*' is not a pointer-to-object type". I don't want to cast the pointer because the whole point of using a pointer is that it is generic.

void print_string(char *string, void *variable) {
  Serial.print(string);
  Serial.print(": ");
  Serial.print(*variable); # This takes a variable of any type (int, float, double, char *);
  Serial.println();
}

I want to be able to provide an int, double, float or string (char*).


Solution

  • The answer is that you have to cast it despite not wanting to. You are trying to dereference a pointer which points to some memory location, but you aren't giving the compiler any semblance of what the size of that information is when it is void * so it has no way of translating that to the proper assembly instruction for accessing that memory.