Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need an explanation of how pointers work when passing in as function args

Tags:

c

I thought I understood the basics of pointers, but after checking out some documentation on some sqlite3 methods I got thrown, so now I am unsure if my understanding is correct.

Here is a call to an sqlite3 method:

char* dataFilePath = "foobar.sqlite";
if (sqlite3_open(dataFilePath, &database) != SQLITE_OK) {...}   

And here is the function header declaration:

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

Why is it that &database suddenly becomes a pointer to a pointer?

Another method call to close the database connection is: sqlite3_close(database);

With the following at the function header:

int sqlite3_close(sqlite3 *);

Why is this just a pointer, when I pass in a pointer? Would this not be a pointer to a pointer?

From all examples I have seen it always seemed the inverse of the functions above, ie.

// function
void foo(someDataType *bar) { ... }

// function call
foo(&bar);

Thanks for the help.

like image 264
chris Avatar asked Aug 19 '09 17:08

chris


1 Answers

Most likely, sqlite3_open is allocating memory for the database handle. For this reason the function needs a pointer to a pointer to the database handle (sqlite3) so that it can modify the pointer to the database handle. For example:

typedef struct { /*...*/ } sqlite3;

int sqlite3_open(const char *filename, sqlite3 **ppDb) {
    /* ... */

    // Allocate memory for the database handle.
    *ppDb = (sqlite3 *)malloc(sizeof(sqlite3));

    /* ... */
    return 0;
}

However, sqlite3_close only needs a single pointer to free the memory:

int sqlite3_close(sqlite3 *pDb) {
    /* ... Cleanup stuff ... */

    free(pDb);

    return 0;
}
like image 144
Andrew Keeton Avatar answered Sep 20 '22 22:09

Andrew Keeton