创建一个char *的2D数组,并使用回调函数中的sqlite数据填充它 [英] Creating an 2D Array of char* an fill it with data from sqlite in callback function
问题描述
在我的函数中,我用callback
函数调用rc = sqlite3_exec(db, sqlStatement, callback, &a, &zErrMsg);
函数.
在此callback
函数中,我想用数据库中的数据填充char *的2D数组.
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"]
这是我以前的问题
推荐答案
我没有找到专门的文档,但是传递到回调中的argv
字符串似乎只有在回调返回之前才有效.我不知道SQLite可以如何工作-回调函数不负责管理这些字符串的内存,因此SQLite必须在内部进行操作.
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.
因此,不要在数组中记录原始的字符串指针,而是复制字符串,并存储指向重复项的指针. MSVC ++提供了strdup()
,因此您可以通过替换...
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];
...和...
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.
这篇关于创建一个char *的2D数组,并使用回调函数中的sqlite数据填充它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!