在下面的ANSI代码中,我如何将矢量conns[]从固定大小转换为动态分配(例如,可能通过使用malloc()和free()函数)?
#include <stdio.h>
#include <string.h>
#include "libpq-fe.h"
#define MAX_DATABASES 20
int main(int argc, char **argv)
{
PGconn *conns[MAX_DATABASES]; // fixed-size vector
int i, ndbs;
ndbs = 3; // this value may vary
memset(conns, 0, sizeof(conns));
// instantiate connections
for (i = 0; i < ndbs; i++) {
conns[i] = PQconnectdb("dbname=template1");
}
// release connections
for (i = 0; i < ndbs; i++) {
fprintf(stdout, "%d) %p\n", i + 1, conns[i]);
if (conns[i])
PQfinish(conns[i]);
conns[i] = NULL;
}
return 0;
}PGconn类型实际上是从/src/interfaces/libpq/libpq-fe.h导入的类型定义结构
typedef struct pg_conn PGconn;pg_conn是在/src/interfaces/libpq/libpq-int.h中找到的结构
struct pg_conn
{
char *pghost;
char *pghostaddr;
char *pgport;
char *pgunixsocket;
...
};上面的代码成功工作,尽管是固定大小的。可以使用以下指令进行编译(需要PostgreSQL源代码):
gcc -I/usr/src/postgresql-9.3/src/interfaces/libpq -I/usr/src/postgresql-9.3/src/include pqc.c -L/usr/src/postgresql-9.3/src/interfaces/libpq -lpq -lpthread -o pqc发布于 2015-12-24 10:28:20
您不必更改太多,只需使用calloc即可
PGconn** conns = calloc(MAX_DATABASES, sizeof(PGConn *));然后记住在最后使用free(conns)。
您不需要memset(),因为calloc()已经使用0s初始化了数组。
发布于 2015-12-24 10:31:14
你可以这样做
PGconn **connections;
size_t number_of_connections;
number_of_connections = 10; // Do not exceed max_connections
// from postgresql.conf
// (default 100)
connections = malloc(number_of_connections * sizeof(*connections));
if (connections == NULL)
return -1; // Allocation error, cannot continue
for (size_t i = 0 ; i < number_of_connections ; ++i)
connections[i] = PQconnectdb("dbname=template1");
// Do whatever you want with connections, and free
for (size_t i = 0 ; i < number_of_connections ; ++i)
PQfinish(connections[i]);
free(connections);您不需要设置所有指向NULL的指针,如果PQconnectdb()失败,它们将自动设置,因此您可以在尝试使用连接之前进行检查。
https://stackoverflow.com/questions/34446487
复制相似问题