Created
October 30, 2012 22:53
-
-
Save antoinealb/3983626 to your computer and use it in GitHub Desktop.
Example of a 2 dimensional array allocation in C for the Informatics I course in MT section, EPFL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
int main(void) { | |
/* Programme d'exemple qui alloue un tableau 3x3 */ | |
int sizeX = 3; | |
int sizeY = 3; | |
int **tab; /* ** Pour dire que c'est un tableau de pointeurs, c'est a dire un tableau de tableau */ | |
int i; | |
/* On alloue la premiere dimension du tab, noter le sizeof(int *) */ | |
tab = malloc(sizeof(int *) * sizeX); | |
if(tab == NULL) { | |
printf("malloc() failed.\n"); | |
return -1; | |
} | |
/* Ensuite on alloue la deuxieme dimension c'est a dire que pour chaque ligne on alloue la colonne correspondante. */ | |
for(i = 0;i < sizeX; i++) { | |
tab[i] = malloc(sizeof(int) * sizeY); | |
if(tab[i] == NULL) | |
printf("malloc() failed.\n"); | |
return -1; | |
} | |
} | |
/* On peut maintenant acceder au tableau ainsi : */ | |
tab[1][1] = 42; | |
/* On fait quelque chose avec le tableau ici... */ | |
/* Une fois fini, il faut liberer le tableau. | |
Pour ca on ne peut pas juste faire free(tab). */ | |
for(i=0; i<sizeX;i++) | |
free(tab[i]); | |
free(tab); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment