Is there any way to malloc a large array, but refer to it with 2D syntax? I want something like:
int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICV
Working from Tim's and caf's answers, I'll leave this here for posterity:
#include <stdio.h>
#include <stdlib.h>
void Test0() {
int c, i, j, n, r;
int (*m)[ 3 ];
r = 2;
c = 3;
m = malloc( r * c * sizeof(int) );
for ( i = n = 0; i < r; ++i ) {
for ( j = 0; j < c; ++j ) {
m[ i ][ j ] = n++;
printf( "m[ %d ][ %d ] == %d\n", i, j, m[ i ][ j ] );
}
}
free( m );
}
void Test1( int r, int c ) {
int i, j, n;
int (*m)[ c ];
m = malloc( r * c * sizeof(int) );
for ( i = n = 0; i < r; ++i ) {
for ( j = 0; j < c; ++j ) {
m[ i ][ j ] = n++;
printf( "m[ %d ][ %d ] == %d\n", i, j, m[ i ][ j ] );
}
}
free( m );
}
void Test2( int r, int c ) {
int i, j, n;
typedef struct _M {
int rows;
int cols;
int (*matrix)[ 0 ];
} M;
M * m;
m = malloc( sizeof(M) + r * c * sizeof(int) );
m->rows = r;
m->cols = c;
int (*mp)[ m->cols ] = (int (*)[ m->cols ]) &m->matrix;
for ( i = n = 0; i < r; ++i ) {
for ( j = 0; j < c; ++j ) {
mp[ i ][ j ] = n++;
printf( "m->matrix[ %d ][ %d ] == %d\n", i, j, mp[ i ][ j ] );
}
}
free( m );
}
int main( int argc, const char * argv[] ) {
int cols, rows;
rows = 2;
cols = 3;
Test0();
Test1( rows, cols );
Test2( rows, cols );
return 0;
}
The compiler and runtime have no way of knowing your intended dimension capacities with only a multiplication in the malloc call.
You need to use a double pointer in order to achieve the capability of two indices. Something like this should do it:
#define ROWS 400
#define COLS 200
int **memory = malloc(ROWS * sizeof(*memory));
int i;
for (i = 0; i < ROWS; ++i)
{
memory[i] = malloc(COLS * sizeof(*memory[i]);
}
memory[20][10] = 3;
Make sure you check all your malloc return values for NULL returns, indicating memory allocation failure.