Due to various restrictions, I have a method which only accepts an int argument. However, I want to pass this method a Struct.
So far, I have…
main(int argc, char* argv){
Somestructure * name;
//Name is malloced, things are put in it, etc.
int address = (int) &name;
method(address);
}
void method(int arg){
Somestructure* thisStruct = (Somestructure*) arg;
//Do stuff with thisStruct.
}
I thought this would assign thisStruct to point to the same struct as name in the main method, however when I attempt to use thisStruct in method, I get a Bus Error.
When I used this code…
int structAddress = (int) &thisStruct;
printf("[Method] Address : %d\n", structAddress);
It seems as though the addresses of name (inside main) and that of thisStruct (inside method) are different.
I’m a little new to C, but, does anyone have any idea what’s going on here?
This code will only run on a 32-bit system, so I need not worry about any 64-bit int/address problems.
Your problem is that you passed in
&name, which is a pointer to a pointer to the struct. So, in themethod, you are accessing theSomestructure **as if it was aSomestructure *.Just pass in
(int)name.(P.S. the usual way to define a “generic argument” is to use
void *.)