Search code examples
cmultidimensional-arraydynamic-memory-allocation

How to declare a 2d Array without knowing the dimensions?


I have a C programming assignment in which I have to read from a text file and store the input in a 2d array. However, the text file only contains the matrix, and 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. However, this matrix is guaranteed to be a square one. I've been searching the internet for several hours but I can't come up with a solution. How can I store this matrix in a 2d array, which has dynamic dimensions, when tested with several input files?


Solution

  • 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.