问题
Please correct me where I understood wrong.
I read this answer https://stackoverflow.com/a/833124/5175709 and what I understood was that since the object could expand and run out of space then the memory location my also change.But here two sqlite3 syntaxes are referencing to the object differently. WHY?
sqlite3_open we have: sqlite3 **ppDb
SQLITE_API int SQLITE_STDCALL sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
And for sqlite3_prepare we have: sqlite3 *db
SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
sqlite3 *db, /* Database handle */
const char *zSql, /* SQL statement, UTF-8 encoded */
int nByte, /* Maximum length of zSql in bytes. */
sqlite3_stmt **ppStmt, /* OUT: Statement handle */
const char **pzTail /* OUT: Pointer to unused portion of zSql */
回答1:
sqlite3_open
needs to somehow give you a database connection object; i.e. a sqlite3
object.
To prevent people from accessing the internals, sqlite3.h
declares sqlite3
as an opaque struct. This means that you cannot allocate space for a sqlite3
since you don't know what it holds; the SQLite library must allocate it for you and give you a pointer to it (sqlite3*
).
So now we have a hypothetical function sqlite3* sqlite3_open(...);
, which opens a DB and returns a pointer to the connection object. But hold on; what if an error occurs? We could return NULL
, but how is the developer supposed to distinguish a "database doesn't exist" error from a "database is read only", "database is corrupted", or other errors?
So instead, sqlite3_open
returns an integer return code, and writes the connection pointer to the memory that the ppDB
parameter points to if opening succeeded.
sqlite3_open
is usually used like this:
sqlite3* myDB;
int status = sqlite3_open("/path/to/db", &myDB);
if(status != SQLITE_OK) {
// error occured
return;
}
// sqlite3_open wrote a database pointer to myDB, use it here
status = sqlite3_prepare_v2(myDB, "SELECT * FROM whatever", -1, NULL, NULL);
// ...
来源:https://stackoverflow.com/questions/36610518/why-is-that-for-sqlite3-open-we-use-double-pointer-and-for-sqlite3-prepare-we