0

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?

Community
  • 1
  • 1
Chortle
  • 171
  • 11
  • There are lots of horrible bugs in this code. Why are you using C? – CL. Mar 16 '15 at 09:53
  • Agreed hence why I'm trying to find out the simplest way to store sql data in an array. As to the why agreed something like python would probably be more straight forward but essentially the thing is written in C with the sqlcipher lib handling encryption. – Chortle Mar 16 '15 at 18:02
  • Your problem is not so much how to use SQLite but the basic understanding of how pointers and arrays work in C. Try [Pointers in C: when to use the ampersand and the asterisk?](http://stackoverflow.com/q/2094666/11654) and [C dynamically growing array](http://stackoverflow.com/q/3536153/11654). Also something like [The C Programming Language](http://cm.bell-labs.com/cm/cs/cbook/). – CL. Mar 16 '15 at 21:21
  • Thanks for the guidance I am certainly not clear on dynamic arrays and pointers still make my head spin kudos for not just supplying the answer. I did the "learn C the hard way" tutorials and found being steered where to look considerably more beneficial to my learning than solution on a plate! - thanks! – Chortle Mar 21 '15 at 00:07

0 Answers0