Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //after last post I just asked myself "how about a 3D array, I have never done something like this"
- //Challenge accepted
- //And I'm surprised now
- #include <stdio.h>
- #include <stdlib.h>
- //for variable m, you need to know the number os columns and height!
- void testOne(int m[][2][5], int r, int c, int h) {
- int x, y, z, a = 0;
- for (x = 0; x < r; x++) {
- for (y = 0; y < c; y++) {
- for (z = 0; z < h; z++) {
- m[x][y][z] = ++a;
- }
- }
- }
- }
- int* testTwo(int r, int c, int h) {
- int* m;
- int x, y, z, a = 0;
- m = malloc(sizeof(int) * c * r * h);
- if (m == NULL) {
- printf("Error allocating memory!");
- exit(1);
- }
- //that's funny, I never though it's like this :o
- //I needed a paper to make some maths
- for (x = 0; x < r*(h + c); x += (h + c)) {
- for (y = 0; y < c * h; y += h) {
- for (z = 0; z < h; z++) {
- m[x + y + z] = ++a;
- }
- }
- }
- /*
- alternative
- for (z = 0; z < h; z++) {
- for (y = 0; y < c; y++) {
- for (x = 0; x < r; x++) {
- m[z * (r*r) + y * c + x] = ++a;
- }
- }
- }
- */
- return m;
- }
- int main() {
- int a[2][2][5], x, y, z, rows = 2, cols = 2, height = 5;
- int* b = NULL;
- testOne(a, rows, cols, height);
- for (x = 0; x < rows; x++) {
- for (y = 0; y < cols; y++) {
- for (z = 0; z < height; z++) {
- printf("%d ", a[x][y][z]);
- }
- printf("\n");
- }
- }
- printf("\n\n\n");
- b = testTwo(rows, cols, height);
- for (x = 0; x < rows*(height + cols); x += (height + cols)) {
- for (y = 0; y < cols * height; y += height) {
- for (z = 0; z < height; z++) {
- printf("%d ", b[x + y + z]);
- }
- printf("\n");
- }
- }
- free(b);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement