I wrote a c code compatible(hopefully) with most c++ compilers. I submit a complete fully working program. The objective is to use the heap memory and write some random data there,it is a 2D array. Questions:
1)I would like some feedback for my code. I would also love to see your tweaks/improvements(if any) to my code so as it will become better, more 'pro'.
2)I am having trouble on how to come up with a working code for a 3D/4D array. Some quality help would be nice.
//CREATES A 2D ARRAY IN THE HEAP MEMORY WITH THE HELP OF AN ARRAY OF POINTERS.
#include <stdlib.h>
#include <cstdio>
#include <cstring>
usingnamespace std;
int main ()
{
int **p, i, j, n, m;
// ENTER 2D DIMENSIONS OF THE ARRAY
printf( "enter number rows: \n" );
scanf( " %d",&n );
printf( "\nenter number of cols: \n" );
scanf( " %d", &m );
// CREATE A 2D ARRAY IN TWO STEPS.FIRST,
//DEFINE AN ARRAY OF POINTERS.THIS ALSO DEFINES THE NUMBER OF ROWS OF ARRAY
p = ( int** )calloc( n, sizeof(int*) );
//CHECK IF THERE IS ENOUGH AVAILABLE HEAP MEMORY
if( p == NULL )
{
puts( "failed.Not enough dynamic memory." );
exit(-1);
}
// DEFINE THE NUMBER OF COLUMNS FOR THE 2D ARRAY.
for( i=0; i<n; i++ )
{
p[i] = ( int* )calloc( m, sizeof(int) );
// CHECK AGAIN IF THERE IS ENOUGH HEAP MEMORY
if( p[i] == NULL )
{
puts( "lack of memory.Failure." );
exit(-2);
}
}
// FILL UP THE ARRAY WITH SOME RANDOM VALUES.
for( i=0; i<n; i++ )
{
for( j=0; j<m; j++ )
*(*(p+i)+j) = 1 + rand() % 5; // TIP: *(*(p+i)+j) <=> p[i][j]
}
//DISPLAY THE ARRAY IN THE STDOUT
printf( "\nresults:\n" );
for( i=0; i<n; i++ )
{
for( j=0; j<m; j++ )
printf( "%d ", *(*(p+i)+j) );
putchar('\n');
}
//RELEASE DYNAMICALLY ALLOCATED MEMORY.
for( i=0; i<n; i++ )
free(p[i]);
free(p);
return 0;
}
DON'T TYPE YOUR COMMENTS IN ALL CAPS. IT IS ANNOYING TO READ.
I don't know much about C; I'm more of a C++ person. I would like to ask, why are you using C instead of C++? Generally, you should only use C if you cannot use C++.
Line 12: m and n are not particularly meaningful names. A simply change to something like nr and nc would be more indicative for number of rows and number of columns.
Line 31: Since you're filling the array at line 43, there is no need to use calloc instead of malloc. A trivial performance difference in this program, but something to keep in mind when repeatedly allocating memory.
Line 43: I don't see srand() called anywhere to initialize the RNG.
Line 43,50: The pointer arithmetic is painful to read.
And as LB said, I don't understand why you're using C instead of C++.