I have looked to see if this question has been asked before I found this but it didn't seem to be the same question. It has me stumped. What is a good way to pass data from an SQL result to a dynamic array stored in a struct?
Say I have a struct called foo; I aim to populate **bar1
with ints from a SQL database and **bar2
with strings.
typedef struct {
int len; // Number of rows in the table
int **bar1;
char **bar2;
} foo;
I initialize the array with the number of rows so when I select bar1[1]
and bar2[1]
I get the data from the second row in my table (as arrays begin at [0]).
foo* init_foo(int *len) {
foo *f = malloc(sizeof(foo)); // I only need one foo for data
f->bar1 = malloc(sizeof(int*)*len); // len = num of rows returned
f->bar2 = malloc(sizeof(char*)*len);
return f;
}
I run a SELECT (*) FROM TABLE
query to obtain the data and store it in a pointer
int *bar2tmp = malloc(sizeof(int*));
bar2tmp = (int*)(intptr_t)sqlite3_column_int(stmt, 0);
char *bar2tmp = (char*)malloc(sizeof(char*));
bar2tmp = (char*)sqlite3_column_text(stmt, 1);
I loop the above running sqlite3_step
each time until I get SQLITE_DONE
and each loop add the results to the array using a function that does the following
for(i = 0; i < len; i++) {
foo->bar1[i] = bar1tmp;
foo->bar2[i] = bar2tmp;
}
Then finally when I'm done with the data I free using
for(i = 0; i < len; i++) {
free(foo->bar1[i]);
free(foo->bar2[i]);
}
I've tried this in practice with no joy and many a valgrind leak. Does anyone have any suggestions how this might be achieved?