在下面的 ANSI C 代码中,我如何将 vector 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结构:
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
最佳答案
你可以这样做
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()
失败,它们将自动设置,因此您可以在尝试使用之前检查一下连接。
关于C - 将结构的固定大小 vector 转换为动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34446487/