I'm trying to store table(stored in a file) into memory. I have here my edited code for simplicity. Im running into segmentation fault so I think it has to do something with that I try to store values without declaring the arrays actually. But I read it shouldn't be a problem as struct arrays are dynamic on their own? I don't really know. So in function addcelltoTable I tried some reallocating, but unsuccessfully. Can you help me understand memory allocating and maybe pointers a little more?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
typedef struct Cells
{
bool selected;
char *Content;
} cell;
typedef struct Rows
{
int someint;
cell cells[];
} row;
typedef struct Tables
{
int NumberOfColumns;
int NumberOfRows;
row rows[];
} table;
void addCellToTable(table *dataTable, char *cellContent, int row, int column)
{
if (row > dataTable->NumberOfRows)
{
dataTable->NumberOfRows = row;
}
if (column > dataTable->NumberOfColumns)
{
dataTable->NumberOfColumns = column;
}
*dataTable->rows[row].cells = (cell*)realloc(dataTable->rows[row].cells, column*sizeof(char*)+1); //here I'm trying to realloc array of cells , error: incompatible types when assigning to type ‘cell’ {aka ‘struct Cells’} from type ‘cell *’ {aka ‘struct Cells *’}
//*dataTable->rows = (row*)realloc(dataTable->rows, (sizeof(dataTable->rows)*sizeof(char*))); //realloc array of rows ?
*dataTable->rows[row].cells[column].Content = *cellContent;
printf("%d : %d : %lu : %s\n", row, column, strlen(dataTable->rows[row].cells[column].Content), dataTable->rows[row].cells[column].Content);
}
int main()
{
char numberitoa[10];
table dataTable;
/*dataTable.NumberOfColumns=0;
dataTable.NumberOfRows=0;
dataTable.rows[0].someint=0;
dataTable.rows[0].cells[0].selected=false;
dataTable.rows[0].cells[0].Content="";*/
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
sprintf(numberitoa, "%d", rand());
addCellToTable(&dataTable, numberitoa, i, j);
}
}
for (int i = 0; i < dataTable.NumberOfColumns + 1; i++)
{
for (int j = 0; j < dataTable.NumberOfRows + 1; j++)
{
printf("main: %d, %d, %s\n", i, j, dataTable.rows[i].cells[j].Content);
}
printf("\n");
}
return 0;
}
cell cells[];tocell *cells;and similar forrows. Don't you get compiler warnings?