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:
Code:
typedef struct {
int ov3;
} ENV;
and a type like this:
Code:
typedef void * SQLHENV;
And then inside sqliteodbc.c it has 2 important functions, and the code of the 2 functions is as follow:
The first one is:
Code:
SQLAllocHandle(SQLHENV *env)
{
ENV *e;
e = (ENV *) malloc(sizeof (ENV));
*env = (SQLHENV) e;
}
And the second one is:
Code:
SQLSetEnvAttr(SQLHENV env)
{
ENV *e;
e = (ENV *) env;
e->ov3 = 1;
}
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:
foo (SQLHENV env)
{
ENV *e;
e = (ENV *) env;
if (e->ov3 == 1)
/*do something here*/
}
That is the way functions in sqliteodbc.c 'communicate'. And I think it is quite easy to understand.
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:
Code:
#include "sqliteodbc.h"
main() {
SQLHENV env;
ENV *ptest;
SQLAllocHandle(&env);
SQLSetEnvAttr(env);
ptest = (ENV *) env;
printf("%d\n", ptest->ov3);
}
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'?
Thanks in advance!