1

I have a C programming assignment which i have to read from a text file and store the input in a 2d array. But text file only contains the matrix, stores no information about rows and columns. My program will be tested with several inputs so the 2d array shouldn't have a fixed size. But this matrix guaranteed to be a square one. I've been searching the net for several hours but couldn't come up with a solution. So how can i store this matrix in a 2d array which has dynamic dimensions when tested with several input files?

  • Is each row in own separate line of the file? – Vlad from Moscow Oct 13 '17 at 23:52
  • 2
    If the file guarantees that it will be a square matrix, just read the first line, store it somewhere, then count how many items the first line contains. You have your size then put all the data (including the first line you just stored) into your newly created matrix. – Adam Oct 13 '17 at 23:55
  • 1
    Read the text file first, to determine the number of dimensions, then declare the array, then read the text file again to get the data? – M.M Oct 13 '17 at 23:55
  • Use a Dynamic array – Erik W Oct 14 '17 at 00:11
  • @McNight i thought of that but i couldn't implement it. The problem is when i read the first line store the count of it and create the matrix accordingly i can't store the data at the same time – Gökberk Şahin Oct 14 '17 at 09:18
  • Why not ? Just create a simple loop. By the way, it's more an algorithmic question than a C question. – Adam Oct 14 '17 at 10:49
  • I solved it by reading file two times. I'm searching dynamic allocation, it seems more efficient. Thanks for your help! – Gökberk Şahin Oct 14 '17 at 18:41
  • "The problem is when i read the first line store the count of it and create the matrix accordingly ..." --> post that code, else this is far too broad. – chux - Reinstate Monica Oct 19 '17 at 15:56

1 Answers1

2

NOTE: From the phrasing, this seems like a homework question. For that reason, I won't post any direct code.

Your matrix is guaranteed to be square, so that means you will have the same number of rows as columns. That means you only have to scan the first line in order to know how many rows and how many columns are needed.

Let us assume that your matrix will be stored in a .csv (comma-separated variable) file. Your data is

n1, n2

n3, n4

Simply read the file as plain text, counting how many delimiters you find before the end of the line. In this case, you found 1 comma in the first row which obviously means you have 2 entries and therefore 2 columns by 2 rows; if you had 3 commas, you would have 4 entries and therefore 4 columns by 4 rows.

n1, n2, n3, n4

n5, n6, n7, n8

n9, n10, n11, n12

n13, n14, n15, n16

From there, you just have to malloc an n by n array of the size you just computed.

Scott Forsythe
  • 360
  • 6
  • 18