C Create Dynamic 2D array

In my last post, I create code to create 2D array in C++. Now, I try to create dynamic 2D array in C. Algorithm to create dynamic 2D array in C or C++ is same. This is a code to create dynamic 2D array in C :

float **arrayf_create(int row, int col)
{
	int i;
	float **mat=NULL;

	/* allocate pointers to rows */
	mat = (float **) malloc((row*sizeof(float*)));
	if (!mat) {
		fprintf(stderr, "matrixf_create : error allocation row");
		exit(0);
	}

	/* allocate rows and set pointers to them */
	mat[0]=(float*) malloc((row*col)*sizeof(float));
	if (!mat[0]) {
		fprintf(stderr, "matrixf_create : error allocation column");
		exit(0);
	}

	for(i=1; i<row; i++)
		mat[i]=mat[i-1] + col;

	/* return pointer to array of pointers to rows */
	return mat;
}

After you create dynamic 2D array in C, you can use this code to free 2D array in C :

void free2Array_float(float **mat)
{
    free (mat[0]);
    free (mat);
}

Add a Comment

Your email address will not be published. Required fields are marked *