Strizzi Strizzi - 1 month ago 5
C Question

Creating an 2D Array of char* an fill it with data from sqlite in callback function

In my function I call the

rc = sqlite3_exec(db, sqlStatement, callback, &a, &zErrMsg);
function with the
callback
function.
In this
callback
function I want to fill a 2D Array of char* with the data from the database.

struct mytable
{
char ***data;
size_t dim;
};

static int callback(void *data, int argc, char **argv, char **azColName)
{
struct mytable *old = (mytable *)data;
char ***temp;

old->dim++;
temp = (char ***)realloc(old->data, old->dim * sizeof(*old->data));
if (temp)
{
old->data = temp;
old->data[old->dim - 1] = NULL;
}
else
{
logging_logError("Kein virtueller RAM mehr vorhanden ... !", __FILE__);
return EXIT_FAILURE;
}

for (int i = 0; i < old->dim; i++)
{
char **temp2 = (char **)realloc(old->data[i], sizeof(argv) * sizeof(*old->data[i]));

if (temp2)
{
old->data[i] = temp2;
old->data[i][argc - 1] = NULL;
}
else
{
logging_logError("Kein virtueller RAM mehr vorhanden ... !", __FILE__);
return EXIT_FAILURE;
}
}

/*Here I try to store the data from each column
in the corresponding position in the 2D array of char* */
for (int i = 0; i < argc; i++)
{
char *s = argv[i];
temp[old->dim - 1][i] = s;
}
return 0;
}


When I print out the data I returned, I get some mysterious signs.
What I want to have is something like this (in array structure):

["1"]["Paul"]["street 1"]["some address"]
["2"]["Anna"]["street asdf"]["some address"]
["3"]["Martin"]["street bfg"]["some address"]


EDIT:
This was my previous question

Answer

I don't find it documented specifically, but it seems probable that the argv strings passed into your callback are good only until the callback returns. I don't see how SQLite could work otherwise -- the callback is not responsible for managing the memory for those strings, so SQLite must do so internally.

Therefore, instead of recording the original string pointers in your array, duplicate the strings, and store pointers to the duplicates. MSVC++ provides strdup(), so you might achieve that by replacing ...

        char *s = argv[i];

... with ...

        char *s = strdup(argv[i]);

. Do be aware that by doing so you assume responsibility for freeing those strings when you're done with them.