---
name: "dynarr"
section: "3pub"
platform: "linux"
package: "publib-dev"
version: "0.40-4"
release: "Debian 13 (Trixie)"
platforms: ["linux"]
url: "https://new.carta.tech/dynarr"
---

# dynarr(3pub)

simple dynamic arrays

## NAME

dynarr, dynarr\_init, dynarr\_resize, dynarr\_free - simple dynamic arrays

## SYNOPSIS

\#include \<publib.h\>

```
void dynarr_init(struct dynarr *da, size_t elsize);
int dynarr_resize(struct dynarr *da, size_t newsize);
void dynarr_free(struct dynarr *da);
```

## DESCRIPTION

These functions make it easier to use dynamic arrays, i.e., arrays that are allocated with [*malloc*(3)](/malloc/3.md) and resized with [*realloc*(3)](/realloc/3.md). Below is a typical code fragment for implementing a dynamic array that is resized as more input is read.

```
char *p, *line;
size_t alloc, len;
len = 0;
alloc = 1024;
if ((line = malloc(alloc)) == NULL) abort();
while (fgets(line + len, alloc-len, stdin) != NULL) {
	len = strlen(line);
	alloc += 1024;
	if ((p = realloc(alloc)) == NULL) abort();
	alloc = p;
}
```

(The error handling is intentionally simplified.)  Below is the above fragment with the *dynarr*(3).

```
struct dynarr da;
dynarr_init(&da);
while (fgets((char *)da.data + da.used, da.alloc-da.len, stdin) != NULL) {
	da.used = strlen(da.data);
	if (dynarr_resize(&da, da.alloc + 1024) == -1) abort();
}
```

The code is a bit simpler, and all the memory allocation details and most of the error checking code is hidden away.

The dynamic array is represented by a *struct dynarr*:

```
struct dynarr {
    void *data;
    size_t alloc, used;
};
```

The interface to the dynamic allocation has intentionally been made unopaque.

*dynarr\_init* initializes a struct dynarr to be an empty array, *dynarr\_resize* sets its size to be *newsize*, and *dynarr\_free* frees the array (it will become an empty array again).

## RETURNS

*dynarr\_resize* returns -1 if it failed, 0 if it succeeded.  It does not change the array in any way if it failed.

## SEE ALSO

publib(3), [malloc(3)](/malloc/3.md), [realloc(3)](/realloc/3.md), [strdup(3)](/strdup/3.md)

## AUTHOR

Lars Wirzenius (lars.wirzenius@helsinki.fi)
