-
Dynamic 2D through fgets
Hello everybody!
My apologies for stupid question in case it is really stupid, but I've just started programming and this task's out of my current knowledge.
I have a dynamically allocated 2D array through
Code:
crossword = (char**)malloc(size_x*sizeof(char*));
for (i = 0; i < size_x; i++)
crossword[i] = (char*)malloc(size_y*sizeof(char));
The problem is - I have to figure out Size_x and Size_y through reading the input. I've figured 'fgets' would do the best there, but I'm not sure how (especially when I need the input to be stored into the array).
To make clear why I'm having the problems with the input is because the input (this is one of the 5 examples of the task input given) looks like this :
**** (The | stands only to make it easier to see where the new line begins )
Input the 8-directions crossword:
.......iadky.......... | .....lwvnaete......... | ....dqiaw..zss........ | ...gmrlws...nrr....... | ..aogydmi....tce...... | ..yirebqf....dzzjthf.. | .snarhodeislandinwxpp. | .imfeopmississippiejlo | ainigrivtsewawngopvnzb | izcxconnecticutnomrevd | fdssttesuhcassamjggroi | nzafycjanilorachtuosoe | .nghainavlysnnepnolws. | ..xdok.........jjia... | ...lo...........gc....
virginia | southcarolina | pennsylvania | connecticut | newjersey | maryland | vermont | iowa | idaho | mississippi | massachusetts | rhodeisland | westvirginia
****
The input is two columns on one go, I need to store the first column into 2D array 'crossword' and the second column in 2D array 'to_cross', I also have to have dynamically allocated size of both of them to fit the words exactly, but I have to keep dynamically allocating as the program reads the input and stores it.
Could anybody please light on the problem with ideas on how to figure out Size_X (amount of the characters in the line) and Size_Y (amount of the lines) to allocate the 2D array and store the input at the same time? Just the ideas would be greatly appreciated as I do not want to waste anybody's time with coding examples.
Best regards,
Jeff
-
The basic brute-force method is to read the file twice: first to determine the sizes (then do the allocations (don't forget an extra character for the string terminating zero byte)) and second to input data.
-
Or you can use realloc() for setting arrays sizes to right values (for crossword and crossword[i] both) in the process of reading