Created
July 31, 2017 01:28
-
-
Save rsnemmen/f7bf8d66295432845af19eb0f3cbc48c to your computer and use it in GitHub Desktop.
Allocates a 3D array in C and populates it with random numbers. You can use the notation A[i][j][k] to access its elements
This file contains hidden or 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
| /* | |
| Example demonstrating how to allocate and use a multdimensional | |
| array. | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <time.h> | |
| // Method to allocate a 2D array of floats | |
| float*** make_3d_array(int nx, int ny, int nz) { | |
| float*** arr; | |
| int i,j; | |
| arr = (float ***) malloc(nx*sizeof(float**)); | |
| for (i = 0; i < nx; i++) { | |
| arr[i] = (float **) malloc(ny*sizeof(float*)); | |
| for(j = 0; j < ny; j++) { | |
| arr[i][j] = (float *) malloc(nz * sizeof(float)); | |
| } | |
| } | |
| return arr; | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| int i, j, k; | |
| size_t N1=10,N2=20,N3=5; | |
| // allocates 3D array | |
| float ***ran = make_3d_array(N1, N2, N3); | |
| // initialize pseudo-random number generator | |
| srand(time(NULL)); | |
| // populates the array with random numbers | |
| for (i = 0; i < N1; i++){ | |
| for (j=0; j<N2; j++) { | |
| for (k=0; k<N3; k++) { | |
| ran[i][j][k] = ((float)rand()/(float)(RAND_MAX)); | |
| } | |
| } | |
| } | |
| // prints values | |
| for (i=0; i<N1; i++) { | |
| for (j=0; j<N2; j++) { | |
| for (k=0; k<N3; k++) { | |
| printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]); | |
| } | |
| } | |
| } | |
| free(ran); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment