C
C
Clean Coder2019-02-04 12:47:29
C++ / C#
Clean Coder, 2019-02-04 12:47:29

What does this function (computational geometry, C) do?

Hello. Here https://rosettacode.org/wiki/Sutherland-Hodgman_po... is a program for cutting a polygon (subject) with a rectangle (clipper). In it, the polygon is defined by the structure:
typedef struct { int len, alloc; vecv; } poly_t, *poly;
Then there is a function:
void poly_append(poly p, vec v)
{
if (p->len >= p->alloc) {
p->alloc *= 2;
if (!p->alloc) p->alloc = 4;
p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
}
p->v[p->len++] = *v;
}
As far as I understand, it is needed to add a new vertex to the polygon. But here is the meaning of this condition:
if (p->len >= p->alloc) {
p->alloc *= 2;
if (!p->alloc) p->alloc = 4;
p->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);
}
somehow eludes me. That is, I understand that this is for allocating memory, but why exactly, why it is multiplied by 2, 4 is assigned, is not very clear to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2019-02-04
@HustleCoder

It's just one of the memory allocation methods.
If n bytes are not enough, we will allocate 2n. If this is not enough, then 4n, 8n, ... 2 k n.
And 4 is the starting value, it is used if p->alloc is still zero.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question