Skip to content

Instantly share code, notes, and snippets.

@seaneshbaugh
Last active December 11, 2015 17:09
Show Gist options
  • Save seaneshbaugh/4632996 to your computer and use it in GitHub Desktop.
Save seaneshbaugh/4632996 to your computer and use it in GitHub Desktop.
Allocate and print two dimensional array.
#include <stdlib.h>
#include <stdio.h>
struct {
int width;
int height;
char **tiles;
} typedef Floor;
Floor *new_floor(int width, int height) {
if (width <= 0 || height <= 0) {
return NULL;
}
Floor *floor = malloc(sizeof(Floor));
if (floor == NULL) {
return NULL;
}
floor->width = width;
floor->height = height;
floor->tiles = malloc(sizeof(char*) * width);
if (floor->tiles == NULL) {
free(floor);
return NULL;
}
int x;
int y;
for (x = 0; x < width; x++) {
floor->tiles[x] = malloc(sizeof(char) * height);
if (floor->tiles[x] == NULL) {
for (y = 0; y < x; y++) {
free(floor->tiles[y]);
}
free(floor->tiles);
free(floor);
return NULL;
}
for (y = 0; y < height; y++) {
floor->tiles[x][y] = '#';
}
}
return floor;
}
int main(int argc, char **argv) {
int width = 10;
int height = 10;
Floor *floor = new_floor(width, height);
if (floor == NULL) {
return 1;
}
int x;
int y;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
printf("%c", floor->tiles[x][y]);
}
printf("\n");
}
for (x = 0; x < width; x++) {
free(floor->tiles[x]);
}
free(floor->tiles);
free(floor);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment