C - 将结构的固定大小 vector 转换为动态分配

标签 c postgresql vector struct

在下面的 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/

相关文章:

postgresql - 从 docker 外部的客户端连接到 postgres 对用户 postgres 进行了致命密码身份验证

sql - 比较多行的开始和结束日期

C++ 崩溃 :push_back on nested vectors

C++:vector 中的 shared_ptr 没有更新原始的 shared_ptr

c - 程序执行未按预期顺序发生

python - 如何从 SQLAlchemy 中的 id 池中获取每组的前 n 个结果?

c - 使用c代码读取AT COMMAND输出?

c++ - 在 C++ 中使用 vector 给了我一个我无法理解的错误

c++ - Matlab 代码生成 : Does not support anonymous functions

c - 在C中,指向需要访问字节指针列表的结构的指针