我正在从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
如何解决这个问题?提前谢谢。 最佳答案
当您声明一个结构数组时,您可以将其大小指定为元素数。你的案件中的人数。声明时不要使用sizeof(person)
:person personlist[num_fields];
。
您还可以使用变量i
而不进行初始化。将其声明更改为int num_fields, i = 0;
。
注意tempdata.name = row[0];
使name
指向与row[0]
指向相同的数据。您可能需要为name
分配内存,并将row[0]
复制到其中(选中“展开答案”)。
关于c - C动态数组中的段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9466825/