0

我正在尝试将从 MySQL 查询获取的结果存储到结构数组中。不过,我似乎无法让这些类型正常工作,而且我发现 MySQL 文档很难整理。

我的结构是:

struct login_session
{
    char* user[10];
    time_t time;
    int length;
};

我试图获取数据的循环是:

while ( (row = mysql_fetch_row(res)) != NULL ) {
    strcpy(records[cnt].user, &row[0]);
    cnt++;
}

无论我尝试什么,尽管我不断收到错误:

test.c:45: warning: passing argument 1 of ‘strcpy’ from incompatible pointer type
/usr/include/string.h:128: note: expected ‘char * __restrict__’ but argument is of type ‘char **’
test.c:45: warning: passing argument 2 of ‘strcpy’ from incompatible pointer type
/usr/include/string.h:128: note: expected ‘const char * __restrict__’ but argument is of type ‘MYSQL_ROW’

任何指针?

4

1 回答 1

2

多个问题,都与指针和数组有关,我建议您阅读一下。

首先,char * user[10]定义一个包含 10 个char *值的数组,而不是 的数组char,这是我怀疑你想要的。警告甚至说,strcpy()期望一个char *,用户字段本身被视为一个char **

其次,您&与第二个论点中想要的东西相距甚远。

从 mysql.h 头复制:

typedef char **MYSQL_ROW;       /* return data as array of strings */

AMYSQL_ROW是一个数组char数组。Using[]做了一个取消引用,所以你取消引用到 a char *which 是什么strcpy(),但是你使用它获取它的地址&

您的代码应该看起来更像这样:

struct login_session
{
    char user[10];
    time_t time;
    int length;
};

while ( (row = mysql_fetch_row(res)) != NULL ) {
    strcpy(records[cnt].user, row[0]);
    cnt++;
}

我不知道你对来自 mysql 的数据有什么保证,但如果你不能绝对确定这些行是<= 10长字符并且 null ( '\0') 终止,你应该使用它来避免任何溢出数组strncpy()的可能性。user

于 2013-08-29T01:43:13.020 回答