I'm currently trying to write a callback function for a database request. The function is called for every result/database entry/row, and I want to store its 2D array (array of strings/char *) in an array. My current solution looks like this:
Global declaration:
char ***entries;
Allocating memory for the first dimension in a setup function:
entries = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(char **)*200);
I'm working with the Windows API/Win32, basically it's malloc with zeroed memory and the last parameter referring to the size.
Initialising callback count and registering callback function for database execute:
cbCount = 0;
rc = sqlite3_exec(db, sql, insertListEntries, 0, &zErrMsg);
Callback function:
static int insertListEntries(void *NotUsed, int argc, char **argv, char **azColName) {
entries[cbCount] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(argv)*argc);
memcpy(entries[cbCount], argv, sizeof(argv)*argc);
...
cbCount++;
}
Parameters: argc is the size of argv/columns of the data, and argv the string array with the row data. I'm simply copying the memory data of argv into the 3D array.
However, the problem is now that for each callback all previous data sets are overwritten with the current result like this:
Callback 1: entries[0] = dataset1
Callback 2: entries[0] = dataset2, entries[1] = dataset2
...
Any ideas? I'm still trying to learn this concept of the "pointer/array-dualism" and memory allocation, but the best way for me is by doing it practically. Also, I DID study the theory beforehand alot, but I may have missed something.
Edit: added cbCount++;
argv, do they actually get re-used? If they do, then you can't just copyargv, you need to copy each string.argvarray of pointers to strings (char buffers). You stored the pointers to these buffers toentries[0]. If they get re-used and their contents changed, then it looks likeentries[0]changed (the pointers didn't change, but the data at the char buffers they point to did).printf("entries[%d][0]=%p", cbCount, entries[cbCount][0])after yourmemcpyto see the pointer values nicely.