Skip to content

Instantly share code, notes, and snippets.

@rsnemmen
Last active July 31, 2017 01:28
Show Gist options
  • Select an option

  • Save rsnemmen/ffc30eaf5049844964301da0b64b63dd to your computer and use it in GitHub Desktop.

Select an option

Save rsnemmen/ffc30eaf5049844964301da0b64b63dd to your computer and use it in GitHub Desktop.
Demonstrates how to allocate a 2D array in C, populating it with uniform random numbers. You can use the notation A[i][j] to access its elements
/*
Example demonstrating how to allocate and use a multdimensional
array.
Reference: http://pleasemakeanote.blogspot.com.br/2008/06/2d-arrays-in-c-using-malloc.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Method to allocate a 2D array of floats
float** make_2d_array(int nx, int ny) {
float** arr;
arr = (float**) malloc(nx*sizeof(float*));
for (int i = 0; i < nx; i++)
arr[i] = (float*) malloc(ny*sizeof(float));
return arr;
}
int main(int argc, char *argv[])
{
int i, j;
size_t N1=100,N2=200;
// allocates 2D array
float **ran = make_2d_array(N1, N2);
// 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++) {
ran[i][j] = ((float)rand()/(float)(RAND_MAX));
}
}
// prints values
for (i=0; i<N1; i++) {
for (j=0; j<N2; j++) {
printf("A[%d][%d] = %f \n", i,j,ran[i][j]);
}
}
free(ran);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment