我从mysql数据库获取值,我想用返回的每一行组织它.这是我的结构(仅限示例):
typedef struct
{
char* name;
char* etc;
int state;
} person;
Run Code Online (Sandbox Code Playgroud)
和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);
Run Code Online (Sandbox Code Playgroud)
但它返回Segmentation fault如何解决这个问题?提前致谢.
你没有复制字符串.您只是存储指针,一旦释放MySQL结果,这些指针可能会变为无效.
您需要使用strdup()或等效创建字符串的本地副本,现在您只是将指针存储到MySQL的数据中.
如果你没有它,这是一个快速和脏的替代品:
char * my_strdup(const char *string)
{
if(string != NULL)
{
const size_t slen = strlen(string);
char *out = malloc(slen + 1);
if(out != NULL)
{
strcpy(out, string);
return out;
}
}
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
请注意,它没有命名strdup(),因为这是一个保留名称.