In the following ANSI C code, how could I convert the vector conns[]
from fixed-size into dynamically allocated (i.e., perhaps by using malloc()
and free()
functions)?
#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;
}
The PGconn
type is actually a typedef struct imported from /src/interfaces/libpq/libpq-fe.h
:
typedef struct pg_conn PGconn;
The pg_conn
is a struct found in /src/interfaces/libpq/libpq-int.h
:
struct pg_conn
{
char *pghost;
char *pghostaddr;
char *pgport;
char *pgunixsocket;
...
};
The code above works successfully, despite being fixed-size. It can be compiled with the following instruction (PostgreSQL sources needed):
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