I have a C Syntax 101 question. Suppose I have a function which takes one kind of pointer as a argument and returns a different type of pointer, and both pointers point to the same data from within the calling function. For example:
#include <stdio.h>
float* convertPtr(const int *a){
return (float*)a;
}
int main() {
float *ptrF;
int x = 5;
ptrF = convertPtr(&x);
printf("%d ::converted to:: %f\n", x, *ptrF);
return 0;
}
Output of this program is:
5 ::converted to:: 0.000000
So I'm a bit baffled by this. The original data is created within main() and is not changed. The convertPtr() function never alters the data, but should only change the type of the pointer.
I also note that when I step through the code on GDB, the pointer (the address itself) does not change:
Breakpoint 1, main () at exp.c:9
9 int x = 5;
(gdb) p &x
$3 = (int *) 0x7fffffffe224
...continue to after calling convertPtr()...
(gdb) p ptrF
$4 = (float *) 0x7fffffffe224
(gdb)
Yet the value pointed to that data has:
(gdb) p x
$8 = 5
(gdb) p *(&x) // sanity check
$9 = 5
(gdb) p *ptrF
$10 = 7.00649232e-45
(gdb)
So... what the heck? After my convertPtr() function, the pointer has been recast but the value of the pointer has not changed... yet dereferencing the converted pointer seems to be pointing to garbage data. (I'm assuming.)
Does anyone see the issue here? Supposed I HAD to fix my function; how do I do that? Thanks...
-ROA
PS: Apologies if this is a duplicate question. I searched for about an hour for "C", "pointer", "casting", "change value", and the posts I pulled up were all over the map. Sometimes its best to ask your question directly.