Help with malloc in c

Hi, how i put the malloc for the variable c? Look my code.

#include <stdlib.h>

int main()
{
int latim;
int **m;
int i, j, l, c;

printf("Digite o numero de linhas/colunas: ");
scanf("%d %d", &l, &c);

m = (int**) malloc(l*sizeof(int**));

for(i = 0; i< l; i++){
m[i] = (int*) malloc(l*sizeof(int*));
for(j = 0; j < c; j++){
m[i][j] = (int*) malloc(c*sizeof(int*)); //Here...
printf("Digite o elemento %d X %d: ", i, j);
scanf("%d", &m[i][j]);
}
}

for(i = 0; i< l; i++){
m[i] = (int*) malloc(l*sizeof(int*));
for(j = 0; j < c; j++){
printf("%d ", m[i][j]);
}
printf("\n");
}



return 0;
}
> m[i][j] = (int*) malloc(c*sizeof(int*)); //Here...
¿and what's that supposed to do?
m[i][j] is a number, and it is already allocated, because m[i] = (int*) malloc(l*sizeof(int*)); created the row.
First off, 'l' is a horrible variable name, because it looks like other things. Use 'r' for 'rows'.

malloc() allocates bytes. So if you want 12 integers, you need 12 * sizeof(int) bytes.

Your 2D array is really an array of pointers to arrays. That is, each row is made up of an pointer to (an array of) ints:

typedef int * row;

The matrix itself is an array of rows:

typedef row* matrix;

Now you can allocate stuff more easily:

 
m = (matrix) malloc( r * sizeof(row) );
m = (int**) malloc( r * sizeof(int*) );

Each row must then be allocated in your loop:

1
2
3
4
for (i = 0; i < r; i++)
{
  m[i] = (row) malloc( c * sizeof(int) );
}
for (i = 0; i < r; i++)
{
  m[i] = (int*) malloc( c * sizeof(int) );
}

This is so common, why not make a function that does it?

1
2
3
4
5
6
7
8
9
matrix matrix_create( int rows, int cols )
{
  matrix m = (matrix) malloc( rows * sizeof(row) );
  for (int r = 0; r < rows; r++)
  {
    m[r] = (row) malloc( cols * sizeof(int) );
  }
  return m;
}

You should also remember to free() the matrix when you are done. Again, a nice function:

1
2
3
4
5
6
7
8
9
matrix matrix_free( matrix m, int rows, int cols )
{
  for (int r = 0; r < rows; r++)
  {
    free( m[r] );
  }
  free( m );
  return nullptr;
}

Now you have easy to use code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
  matrix m;
  int rows, cols;

  printf("Digite o número de linhas e colunas separadas por um espaço: ");
  scanf("%d %d", &rows, &cols);

  m = matrix_create( rows, cols );

  // do stuff with my matrix
  m[0][0] = -7;

  m = matrix_free( m, rows, cols );
}

Hope this helps.
Topic archived. No new replies allowed.