I’m getting values from mysql database, I want to organize it with each row returned. here’s my struct(example only):
typedef struct
{
char* name;
char* etc;
int state;
} person;
and the MySql:
MYSQL * con;
mysql_connect(&con); //connect to mysql database and set handle to con variable.
MYSQL_ROW row;
MYSQL_RES * result;
int num_fields, i;
mysql_query(con, "select name,etc,state from db.tbl");
result = mysql_store_result (con);
num_fields = mysql_num_fields (result);
person tempdata;
person personlist[num_fields * sizeof(person)]; //the size if the problem, I believe...
while((row = mysql_fetch_row (result))) {
tempdata.name = row[0];
tempdata.etc = row[1];
tenpdata.state = atoi(row[2]);
personlist[i++] = tempdata; // the error line
}
mysql_free_result (result);
mysql_close (con);
but it returns Segmentation fault how to fix this? thanks in advance.
When you declare an array of structures, you specify its size as number of elements. Number of persons in your case. Declare it without
sizeof(person):person personlist[num_fields];.You also use variable
iwithout being initialized. Change its declaration toint num_fields, i = 0;.And note that
tempdata.name = row[0];makesnamepoint to the same data asrow[0]points to. You probably want to allocate memory fornameand copyrow[0]into it (check unwinds answer).