Last active
December 14, 2015 08:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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