sajohn wrote:
I'm fairly new to c programming and am not very clear on pointers and
handles.
I'm not sure what you mean by handle. There's no
such thing in standard C terminology.
Currently, I'm writting a wrapper script and I need to
interface with another application. I have decided that the wrapper
script could use some data structures and have defined a few. The
problem is that the application has defined some pointers that I could
use for my structures that are defined as unsigned long. I thought I
could write some code as follows
unsigned long HANDLE ;
unsigned long *PHANDLE ;
Based on some of the code below I suspect that
the above 2 lines were meant to start with typedef.
typedef struct
{
int i ;
float f ;
} Numbers ;
HANDLE hTest1 ;
PHANDLE *phTest2;
You don't get an error for the last 2 lines above ?
You should. You are declaring hTest1 as having
type HANDLE but there is no such type in the
language nor have you defined one yourself.
Numbers Num ;
hTest2 = (PHANDLE )malloc( HANDLE * ) ;
malloc() accepts an argument of type size_t.
You are giving it a pointer to a type HANDLE
which as I've said above you haven't defined.
Even if your intention was for HANDLE to mean
unsigned long the above line is still wrong and
the compiler should give you an error. Does your
code contain #include <stdlib.hsomewhere ?
hTest1 = ( HANDLE )malloc( sizeof( Num ) ) ;
hTest2->i = 10 ;
The notation -is used when a pointer points to
a structure. hTest2 is not a pointer to a structure.
In fact it's not any sort of object since you have
not given a legal definition for it anywhere. As an
example if you had given the declaration
Numbers *p ;
then you could write
p->i = 5 ; p->f = 3.1 ;
hTest2->f = 127/13 ;
This code fails with an error indicating that I'm pointing to an hTest2
structure instead of a Num structure and cannot find i or f fields.
You should have received a lot more errors than that.
>
Then I thought I could something like this
hTest2->hTest1->i
to retrive the filed data but the results are the same.
I know a lot of this is my lack of understanding of pointers in general
but I was wondering if someone could tell me where I'm going wrong with
this code.
I hope I managed to be of some help but your
misunderstandings are so numerous I'm driven to despair.
Is it even possible to malloc a data structure in memory and
then re-cast its pointer type to an unsigned long?
Strictly speaking you don't malloc a data structure you
malloc memory for a data structure (or something else).
As for recasting its pointer type to unsigned long it might
work depending on your implementation but if you think
it's something you need to do then almost certainly you
are going wrong somewhere.