Hi everybody, when reading and testing the source code of a program I had a question about pointers and addresses.
My OS is Ubuntu 8.04. The program I am talking about is SQLite ODBC driver (and its source code can be downloaded from here). However, to understand my problem, it is not important to know what this program does. I just want to ask about the way it used pointers in its source code.
Basically the source code of this program consists of 2 files: sqliteodbc.c and sqliteodbc.h. Inside sqliteodbc.h it defines a struct like this:
and a type like this:Code:typedef struct { int ov3; } ENV;
And then inside sqliteodbc.c it has 2 important functions, and the code of the 2 functions is as follow:Code:typedef void * SQLHENV;
The first one is:
And the second one is:Code:SQLAllocHandle(SQLHENV *env) { ENV *e; e = (ENV *) malloc(sizeof (ENV)); *env = (SQLHENV) e; }
Then other functions in sqliteodbc.c can obtain the value of ov3 just by being passed to the parameter env. I means they only know the address the void pointer points to, and then they typecast it to ENV*, and then they can access its member, something like this:Code:SQLSetEnvAttr(SQLHENV env) { ENV *e; e = (ENV *) env; e->ov3 = 1; }
That is the way functions in sqliteodbc.c 'communicate'. And I think it is quite easy to understand.Code:foo (SQLHENV env) { ENV *e; e = (ENV *) env; if (e->ov3 == 1) /*do something here*/ }
However, when I tried to reproduce this communication mechanism, I failed.
After being built, this program will be a library, libsqliteodbc.so, and by linking to this library you can use its functions in your code. So I wrote a simple test code like this:
I expected the output from the above printf command would be '1', but it would not. Could you please explain to me why I did not get the value '1'?Code:#include "sqliteodbc.h" main() { SQLHENV env; ENV *ptest; SQLAllocHandle(&env); SQLSetEnvAttr(env); ptest = (ENV *) env; printf("%d\n", ptest->ov3); }
Thanks in advance!



LinkBack URL
About LinkBacks



