C++: allocating a two-dimensional matrix

De Wiki de Calcul Québec
Aller à : Navigation, rechercher
Cette page est une traduction de la page C++ : allocation d'un tableau à deux dimensions et la traduction est complétée à 100 % et à jour.

Autres langues :anglais 100% • ‎français 100%

Allocating a two-dimensional array (imax*jmax), where data is put contiguously in memory, is not trivial in C or C++. Firstly an array of pointers where the number of elements is equal to the number of rows in the array (imax) must be created. After that you should allocate the memory needed to contain imax*jmax elements starting at the first address within the array. Finally you should make sure that the pointers to the first elements of each row point to the correct address.

The following two examples (one in C and the other in C++) show how to create a two-dimensional array with elements of type double precision.


File : allocation2D.c
/*
Allocating a 2D array in C
*/
 
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
 
int main(int argc,char** argv)
{
    int i,j,imax,jmax
 
    /* Declaration of the 2D array */
 
    double **tableau2D;
 
    /* Allocation of the 2D array */
    tableau2D = (double **)malloc(sizeof(double *)*imax)
    tableau2d[0] = (double *)malloc(sizeof(double)*imax*jmax);
    for(i=1;i<imax;i++)
        tableau2D[i]=tableau2D[i-1]+jmax;
 
    /* Using the array */
 
    for(i=0;i<imax;i++)
    {
        for(j=0;j<jmax;j++)
        {
            tableau2D[i][j]=1.0
        }
    }
 
    /* Freeing the allocated memory */
 
    free(tableau2D[0]);
    free(tableau2D);
 
}



File : allocation2D.cpp
//////////////////////////////////////////////////
// Allocating a 2D array in C++
 
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
 
int main(int argc,char** argv)
{
    int i,j,imax,jmax
 
    // Declaration of the 2D array
    double **tableau2D;
 
    // Allocating the 2D array
 
    tableau2D = new double*[imax];
    tableau2D[0] = new double[imax*jmax];
    for(i=1;i<imax;i++)
        tableau2D[i]=tableau2D[i-1]+jmax;
 
    // Using the array
 
    for(i=0;i<imax;i++)
    {
        for(j=0;j<jmax;j++)
        {
            tableau2D[i][j]=1.0
        }
    }
 
    // Freeing the allocated memory
 
    delete [] tableau2D[0];
    delete [] tableau2D;
 
}


Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Ressources de Calcul Québec
Outils
Partager