Reputation: 3
I have a problem, trying to use a char** in a structure, in C language.
The purpose of my code is to keep an historic of strings. The structure has 2 variables:
codeJuste, which is a string of NB_PION chars. codesProposes, which is an array of NB_COUPMAX cases. Each case keep a code which is a string of NB_PION chars.
I'm trying to write into each case of codesProposes but I have an error of Segmentation fault. thank you by advance for trying to help me (Sorry for my english, I'm French).
Here is my testing code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define NB_PION 4
#define NB_COULEUR 4
#define NB_COUPMAX 6
//Définition d'une structure
typedef struct _Partie{
char* codeJuste;
char** codesProposes;
} Partie;
int main (int argc,char** argv[]){
Partie maPartie;
maPartie.codeJuste = malloc((NB_PION+1) * sizeof(char));
strcpy(maPartie.codeJuste,"AAAA");
maPartie.codesProposes = malloc(NB_COUPMAX * ((NB_PION + 1) * sizeof(char)));
strcpy(maPartie.codesProposes[0],"BBBB");
strcpy(maPartie.codesProposes[1],"CCCC");
printf("1:%s \n",maPartie.codeJuste);
printf("2:%s \n",maPartie.codesProposes[0]);
printf("3:%s \n",maPartie.codesProposes[1]);
}
Upvotes: 0
Views: 88
Reputation: 40155
Change to like this:
typedef struct _Partie{
char *codeJuste;
char (*codesProposes)[NB_PION+1];
} Partie;
maPartie.codesProposes = malloc(NB_COUPMAX * sizeof(char [NB_PION+1]));
Upvotes: 1
Reputation: 30146
Change this:
maPartie.codesProposes = malloc(NB_COUPMAX * ((NB_PION + 1) * sizeof(char)));
To this:
maPartie.codesProposes = malloc(NB_COUPMAX * sizeof(char*));
for (i=0; i<NB_COUPMAX; i++)
maPartie.codesProposes[i] = malloc((NB_PION+1) * sizeof(char));
And don't forget to deallocate everything at a later point in the execution of your program:
for (i=0; i<NB_COUPMAX; i++)
free(maPartie.codesProposes[i]);
free(maPartie.codesProposes);
Upvotes: 2