Go Down

Topic: Fiddling with pointers - casting (Read 2170 times) previous topic - next topic

Jodes

May 08, 2013, 08:17 pm Last Edit: May 08, 2013, 08:21 pm by Jodes Reason: 1
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:

Code: [Select]
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!

PaulS

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 *.

Code: [Select]
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.
The art of getting good answers lies in asking good questions.

pYro_65

This should work.

Code: [Select]
write( ( char* ) ptr );

Why not just use char* type instead of the unnecessary long.
Forum Mod anyone?
https://arduino.land/Moduino/

AWOL

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

Jodes

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 :) The cast (char *) worked, thank you very much!

Go Up