I have something of this sort:
int n,m;
scanf("%d %d",&m,&n);
int *arr = malloc(sizeof(int)*n*m);
for(int i=0;i<m*n;scanf("%d",arr+i),i++);
Try this,
int n,m;
printf( "Enter two digits" );
int scanCount = scanf( "%d %d", &m, &n );
if( scanCount < 2 ){
perror("Input");
exit(EXIT_FAILURE);
}
scanCount = 0;
size_t size = sizeof( int ) * n * m;
int * arr = (int *) malloc( size );
if ( arr == NULL ) {
perror("malloc");
exit(EXIT_FAILURE);
};
for( int i = 0; i < m * n; i++ ){
if ( scanf( "%d", arr + i ) )
scanCount++;
}
if( scanCount < m*n ){
perror("Input");
exit(EXIT_FAILURE);
}
for( int i=0; i<n*m; i++ ){
printf( "\nValue at %d : %d\n", i, *( arr + i ) );
}
I have modified the above given program a little bit, and now it works for me. The malloc function expects "std::size_t size" ( we can also provide integer values ) as argument which is the size of the memory we need to allocate. Please visit http://en.cppreference.com/w/cpp/memory/c/malloc for any reference.
Also we should specify the type of the memory we are creating ( otherwise it may produce an error in some compilers, like this "invalid conversion from 'void*' to 'int*'" ). In this case we are creting an array of integers and we can use type cating, for example (int *) malloc( size).
It is better to implement some error handlers for failed memory allocation and inputs through scanf ( check the return values of malloc and scanf )