Skip to content

Instantly share code, notes, and snippets.

@mvasilkov
Last active December 14, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvasilkov/5059285 to your computer and use it in GitHub Desktop.
Save mvasilkov/5059285 to your computer and use it in GitHub Desktop.
This is a demo of 2D arrays in C written for my (imaginary) friend.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int **array2d, n, i, j;
puts("Enter a number:");
scanf("%d", &n);
puts("Thank you, kind sir.");
if (n < 1) {
puts("Go away, I hate you.");
return 9;
}
// Init:
array2d = malloc(n * sizeof(*array2d)); // int *
for (i = 0; i < n; ++i) {
array2d[i] = malloc(n * sizeof(**array2d)); // int
}
// Usage:
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
array2d[i][j] = (i + 1) * (j + 1);
}
}
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
printf("%3d ", array2d[i][j]);
}
puts(""); // newline
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment