<-Back to home
<-Page à Aurélie
<- Computer cheat sheet
<- Fiche Info

Allocation de mémoire en C / Memory allocation in C

int main(int argc, char* (argv[]) )
{
  int i,j;
  int n = 10;
  int m = 20;
  int **t;
  // allocate memory
  t = (int**) malloc ( n * sizeof(int*));
  for (i=0; i<n; i++)
  {
    *(t + i) = (int*) malloc ( m * sizeof(int) );
  }  
  // fill matrix
  for (i=0; i<n; i++)
  {
    for (j=0; j<m; j++)
    {
      *(*(t + i) + j) = i+j;
    }  
  }    
  // print matrix
  for (i=0; i<n; i++)
  {
  for (j=0; j<m; j++)  
  {  
    printf("%d ", t[i][j]);
  }  
    printf("\n");  
  }    
  // free memory
  for (i=0; i<n; i++)
  {
    free(*(t+ i));
  }  
  free(t);
  return 0;
}
January 2003