Fiddling with pointers - casting

Heya,

I’m messing around with pointers for the sake of a better understanding. What I want to do:

  • declare and initialise a string within a function.
  • within that function, assign the address of that string to a globally declared long
  • once the function has exited, see what havoc I can cause by trying to access the data at that address as a string again

Below is the code, including the compiler error. Any idea how I can get this to work? I think I need to cast the ptr variable when passing it to the write function but I’m not sure how to do this:

long ptr;
void setup() {
  initLCD();  
  makeFunctionScopeString();
  write(*ptr); // compiler says "Invalid type argument of 'unary*'
}
void makeFunctionScopeString(){
  char str_fn[4] = "Bla";
  ptr = (long) &str_fn;
}
void loop(){}
void write(char  *str_toLCD){ ... }

Thanks!

Using the correct type in the declaration of the function would be the first step.

You want to point to a char (or char array), you use a char *.

char *ptr = NULL;

You don't use a long. Since your "pointer" isn't a pointer, you can't pretend its a pointer. Use a real pointer.

This should work.

write( ( char* ) ptr );

Why not just use char* type instead of the unnecessary long.

Don't use pointers to automatic variables. Bad things can happen.

Thanks Paul, Pyro, AWOL - I did that intentionally, I’m experimenting to see what can be done. I appreciate that normally one would declare it as a pointer. I’m sure there probably isn’t any good reason to do it the way I’ve done it, and accessing the local variable after the function exists would be an extremely bad idea, but I just want to gain a deeper understanding :slight_smile: The cast (char *) worked, thank you very much!