Bonjour,
Je suis débutant en C, et j'ai un problème avec ce programme ci dessous.
Je pense que le problème est dans cette partie:
Code C/C++ :
matrice init(int nbDeLignes, int nbDeColonnes)
{
int i, i0, i1;
int size_Mat = nbDeLignes*nbDeColonnes;
matrice mat = allouerMatrice();
mat->nbDeLignes = nbDeLignes;
mat->nbDeColonnes = nbDeColonnes;
mat->data = malloc(nbDeLignes*nbDeColonnes*sizeof(int));
/*
ERROR
*/
for(i=0; i< size_Mat; ++i)
(mat->data)[i] = i;
return mat;
}
quand j'essaye d'initialiser la matrice, le programme s’exécute mais ya une erreur d'accès memoire je pense.
Peut être dans l'allocation de l'espace memoire.
Si quelqu'un peut m'aider
Code C/C++ :
#include<stdio.h>
#include<stdlib.h>
typedef double typeDeDonnees;
typedef struct matrice {
int nbDeLignes ;
int nbDeColonnes ;
typeDeDonnees *data;
} * matrice ;
// allocation de l'espace associe a un pointeur vers matrice
matrice allouerMatrice()
{
return (matrice)malloc(sizeof(struct matrice));
}
// initialisation d'une matrice (et allocation dynamique pour les donnees)
matrice init(int nbDeLignes, int nbDeColonnes)
{
int i, i0, i1;
int size_Mat = nbDeLignes*nbDeColonnes;
matrice mat = allouerMatrice();
mat->nbDeLignes = nbDeLignes;
mat->nbDeColonnes = nbDeColonnes;
mat->data = malloc(nbDeLignes*nbDeColonnes*sizeof(int));
/*
ERROR
*/
for(i=0; i< size_Mat; ++i)
(mat->data)[i] = i;
return mat;
}
void affiche(matrice mat)
{
int i0, i1;
int NBL = mat->nbDeLignes;
int NBC = mat->nbDeColonnes;
printf("Nombre de ligne = %d\n",NBL);
printf("Nombre de colonne = %d\n",NBC);
for (i0=0; i0<NBL; i0++){
printf("\n");
for (i1=0; i1<NBC; i1++)
printf("%d ",mat->data[i0*NBC+i1]);
}
}
//addition de deux matrices
matrice addition(matrice mat1, matrice mat2)
{
if ( mat1==NULL || mat2==NULL)
{ // l'un des deux pointeurs n'est pas alloue
fprintf(stderr,"%s:%d> ERREUR: addition",__FILE__,__LINE__);
exit(EXIT_FAILURE);
}
else
{
}
}
// desallocation des matrices
void liberer(matrice mat)
{
if (mat != NULL)
free(mat->data);
free(mat);
}
int main()
{
matrice mat1 = init(3,5);
matrice mat2 = init(3,5);
matrice mat3 = NULL;
affiche(mat1); // ERROR
liberer(mat1);
system("pause");
/* affiche(mat2);
affiche(mat3);
mat3 = addition(mat1,mat2);
affiche(mat3);*/
liberer(mat1);
liberer(mat2);
liberer(mat3);
return EXIT_SUCCESS;
}

