首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C-将结构的固定大小向量转换为动态分配

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

Stack Overflow用户
提问于 2015-12-24 10:24:34
回答 2查看 79关注 0票数 0

在下面的ANSI代码中,我如何将矢量conns[]从固定大小转换为动态分配(例如,可能通过使用malloc()free()函数)?

代码语言:javascript
复制
#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导入的类型定义结构

代码语言:javascript
复制
typedef struct pg_conn PGconn;

pg_conn是在/src/interfaces/libpq/libpq-int.h中找到的结构

代码语言:javascript
复制
struct pg_conn
{
    char *pghost;
    char *pghostaddr;
    char *pgport;
    char *pgunixsocket;
    ...
};

上面的代码成功工作,尽管是固定大小的。可以使用以下指令进行编译(需要PostgreSQL源代码):

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2015-12-24 10:28:20

您不必更改太多,只需使用calloc即可

代码语言:javascript
复制
PGconn** conns = calloc(MAX_DATABASES, sizeof(PGConn *));

然后记住在最后使用free(conns)

您不需要memset(),因为calloc()已经使用0s初始化了数组。

票数 1
EN

Stack Overflow用户

发布于 2015-12-24 10:31:14

你可以这样做

代码语言:javascript
复制
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()失败,它们将自动设置,因此您可以在尝试使用连接之前进行检查。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34446487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档