💾 Archived View for thrig.me › blog › 2024 › 03 › 19 › grid-factory.c captured on 2024-03-21 at 15:41:14.

View Raw

More Information

-=-=-=-=-=-=-

#include <stdio.h>
#include <stdlib.h>

int **
make(size_t x, size_t y)
{
	int **map;
	if (!(map = malloc(x * sizeof(int *)))) abort();
	if (!(map[0] = calloc((size_t) x * y, sizeof(int)))) abort();
	for (size_t i = 1; i < x; i++)
		map[i] = map[0] + i * y;
	return map;
}

void
set(int **gp, size_t rows, size_t cols)
{
	int i = 1;
	for (size_t r = 0; r < rows; ++r)
		for (size_t c = 0; c < cols; ++c)
			gp[r][c] = i++;
}

void
show(int **gp, size_t rows, size_t cols)
{
	for (size_t r = 0; r < rows; ++r) {
		for (size_t c = 0; c < cols; ++c) {
			printf("%d", gp[r][c]);
		}
		putchar('\n');
	}
}

int
main(int argc, char *argv[])
{
	int **blah = make(3, 3);
	set(blah, 3, 3);
	show(blah, 3, 3);
}