我从mysql数据库获取值,我想用返回的每一行来组织它。这是我的结构(仅限示例):
typedef struct
{
char* name;
char* etc;
int state;
} person;
和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);
但它返回Segmentation fault
如何解决这个问题?提前谢谢。
答案 0 :(得分:5)
您没有复制字符串。您只是存储指针,一旦释放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;
}
请注意,它未命名为strdup()
,因为这是一个保留名称。
答案 1 :(得分:2)
声明结构数组时,将其大小指定为元素数。您案件中的人数。在没有sizeof(person)
的情况下声明它:person personlist[num_fields];
。
您还可以使用变量i
而不进行初始化。将其声明更改为int num_fields, i = 0;
。
请注意tempdata.name = row[0];
使name
指向与row[0]
指向的数据相同的数据。您可能希望为name
分配内存并将row[0]
复制到其中(检查解除答案)。
答案 2 :(得分:1)
int num_fields, i;//Then you have not set a initial value to the variable i.
答案 3 :(得分:1)
mysql_num_fields
返回结果集中的列数。 32位系统上的sizeof(person)
大约是12个左右。 i
未初始化。
您需要i
从零开始,并且您需要足够的存储空间,而不是列数的12倍。
答案 4 :(得分:0)
除了前面提到的字符串复制问题:
person personlist[mysql_num_rows(result)];
您需要足够的存储空间来存储行数,而不是字段数。