Hello again!
Again problems with my project this time is the reallocation of a 3d dynamic matrix what is driving me mad... I'm trying to add a new column to the matrix and for this I'm trying to use the realloc routine in the cell pointer to pointer to pointer to char... the project is the same I explained here.
This is what I have so far:
Code:
/* add_column: add a column to table t */
void add_column(table *t){
int i, j;
// Increase columns count
++(t->cols);
t->cell = (char ***) realloc(t->cell, t->rows * sizeof(char **));
if(t->cell == NULL){
printf("\n\t\tERROR: Out of memory\n");
printf("\n\t\tPress any key to exit...\n");
getchar();
exit(EXIT_FAILURE);
}
for(i = 0; i < t->rows; ++i){
t->cell[i] = (char **) realloc(t->cell[i], t->cols * sizeof(char *));
if(t->cell[i] == NULL){
printf("\n\t\tERROR: Out of memory\n");
printf("\n\t\tPress any key to exit...\n");
getchar();
exit(EXIT_FAILURE);
}
for (j = 0; j < t->cols; j++){
t->cell[i][j] = (char *)realloc(t->cell[i][j], NAME_MAX_LEN * sizeof(char));
if(t->cell[i][j] == NULL){
printf("\n\t\tERROR: Out of memory\n");
printf("\n\t\tPress any key to exit...\n");
getchar();
exit(EXIT_FAILURE);
}
}
}
// Name & add new column
printf("\nNew column's name:\n");
printf("\nC%d: ", t->cols);
fflush(stdin);
gets(t->cell[0][t->cols]);
for(i = 1; i < t->rows; ++i){
printf("\nR%d C%d: ", i, t->cols);
fflush(stdin);
gets(t->cell[i][t->cols]);
}
}
Remember I want to add a new column only, (I know the problems of using gets but I'll change that to fgets in a later stage...) the problem I'm having is sometimes the program crashes and I get a segmentation fault (again...)
So first I need to know if the reallocation of memory is done correctly? (Because I'm not used to reallocate 3dimensional arrays) Thank you very much in advance!