C++ 列编号1超出范围0..-1

C++ 列编号1超出范围0..-1,c++,pointers,segmentation-fault,coredump,libpqxx,C++,Pointers,Segmentation Fault,Coredump,Libpqxx,我编写了一个函数,希望在其中传递指向结构数组的指针。我在它里面有new(),我想用从PGresult结构(res)检索到的数据填充它。但是我有错误: column number 0 is out of range 0..-1 column number 1 is out of range 0..-1 column number 2 is out of range 0..-1 column number 3 is out of range 0..-1 Segmentation fault (

我编写了一个函数,希望在其中传递指向结构数组的指针。我在它里面有
new()
,我想用从PGresult结构(res)检索到的数据填充它。但是我有错误:

column number 0 is out of range 0..-1 
column number 1 is out of range 0..-1 
column number 2 is out of range 0..-1 
column number 3 is out of range 0..-1
Segmentation fault (core dumped)
这是我的功能

Database::selectAnnouncements(const int user_id, const char *cat_id, struct announcementStruct **pStruct, int *size) {

*size = PQntuples(res);

struct announcementStruct * ann = new struct announcementStruct[PQntuples(res)];
*pStruct =  ann;
int cr_fnum = PQfnumber(res, "created_on");
int con_fnum = PQfnumber(res, "content");
int cat_fnum = PQfnumber(res, "category");
int rm_fnum = PQfnumber(res, "remove_on");


for (int i = 0; i < PQntuples(res); i++) {
        const char *cr_val = PQgetvalue(res, i, cr_fnum);
        const char *con_val = PQgetvalue(res, i, con_fnum);
        const char *cat_val = PQgetvalue(res, i, cat_fnum);
        const char *rm_val = PQgetvalue(res, i, rm_fnum);
        (*pStruct[i]).creation_date = new char[strlen(cr_val)];
        (*pStruct[i]).content = new char[strlen(con_val)];
        (*pStruct[i]).category = new char[strlen(cat_val)];
        (*pStruct[i]).removal_date = new char[strlen(rm_val)];
        strcpy((*pStruct[i]).creation_date, cr_val);
        strcpy((*pStruct[i]).content, con_val);
        strcpy((*pStruct[i]).category, cat_val);
        strcpy((*pStruct[i]).removal_date, rm_val);
}

for (int i = 0; i < PQntuples(res); i++) {
        printf("%s  ", (pStruct[i]->creation_date));
        printf("  %s  ", (pStruct[i]->content));
        printf("  %s  ", (pStruct[i]->category));
        printf("  %s  ", (pStruct[i]->removal_date));
        printf("\n");
}
PQclear(res);

您肯定忘记了以null结尾字符串。分配strlen+1以适应空值。忘记空值很容易导致错误。像strncpy snprintf这样的函数有助于确保事情更加安全


凯文的评论也是正确的。请确保您获得了此错误的所有12个实例(原始的4个、strcpy中的4个和printf中的4个)

您肯定忘记了以null结尾字符串。分配strlen+1以适应空值。忘记空值很容易导致错误。像strncpy snprintf这样的函数有助于确保事情更加安全


凯文的评论也是正确的。确保您获得了此错误的所有12个实例(原始4个、strcpy中的4个和printf中的4个)

哪里定义了
res
?我将此代码剪切粘贴到一个文件中,但它不会编译。它是否缺少了诸如#include以及函数、结构和类之类的内容?您忘记了空终止字符串,可能还因为
(*pStruct[i])
不符合您的要求。它解除了对pString[i]的引用。你想要
(*pStruct)[i]
res是PGresult类型的,它是libpq API的一部分,我在类中将它声明为一个字段。在哪里定义了
res
?我将此代码剪切粘贴到一个文件中,但它不编译。它是否缺少了诸如#include以及函数、结构和类之类的内容?您忘记了空终止字符串,可能还因为
(*pStruct[i])
不符合您的要求。它解除了对pString[i]的引用。您需要
(*pStruct)[i]
res是PGresult类型,它是libpq API的一部分,我已将其声明为类中的字段。不客气。别忘了投票给凯文。我的功劳只有一半,不客气。别忘了投票给凯文。功劳只有我的一半。
struct announcementStruct *announcements = NULL;
int size;
db.selectAnnouncements(0, "DOGS", &announcements, &size);