Karyna
Karyna

Reputation: 205

create two-dimensional array/matrix using C

I need to read a file with some kind of a matrix from CSV file(number of matrix columns and rows may be different every time) using C. The file will be something like that:

#,#,#,#,#,#,.,#,.,.,.$
#,.,#,.,.,#,.,#,#,#,#$
#,.,#,.,.,.,.,.,.,#,#$
#,.,#,.,.,#,#,#,#,#,#$
#,.,.,#,.,.,.,.,.,.,#$
#,.,.,.,#,.,#,#,.,.,#$
#,.,.,.,.,#,.,.,.,.,#$
#,.,.,.,.,#,.,.,.,.,#$
#,.,.,.,.,.,.,.,.,.,#$
#,#,#,#,#,#,#,#,#,.,#$

I need to read the file and save it to a two-dimensional array to be able to iterate through it and find the path out of the labyrinth using Lee algorithm.

So I want to do somenthing like:

int fd = open (argv[i], O_RDONLY);

    while (read(fd, &ch, 1)) {
     here should be some for loops to find the  number of colums and rows. 
    }

Unfortunately, I don't know how to do that if heigth and width of the matrix is unknown.

I was trying to do that:

while (read (fd, &ch, 1)) {
  for (int i = 0; arr[i] != '\0'; i++) {
    for (int j = 0; j != '\n'; j++) {
      somehow save the values, number of columns and rows.
    }
  }
}

However, number of rows could be greater than number of columns. Any help will be appreciated

Upvotes: 0

Views: 144

Answers (1)

Lundin
Lundin

Reputation: 213513

If the size isn't known but has to be determined as you parse the file, then a simple but a bit naive idea would be to use a char** rows = malloc(n); where n is a sufficiently large number to cover most normal use-cases. realloc if you go past n.

Then for each row you read, store it inside rows[i] through another malloc followed by strcpy/memcpy.

A smarter version of the same would be to first read the first row, find the row length and then assume that all rows in the file have that size. You can do do a char (*rows)[n] = malloc (n * (row_length+1) ); to allocate a true 2D array. This has advantages over the char**, since you get a proper cache-friendly 2D array with faster access, faster allocation and less heap fragmentation. See Correctly allocating multi-dimensional arrays for details about that.

Another big advantage of the char (*rows)[n] is that if you know n in advance, you can actually read/fread the whole file in one go, which would be a significant performance boost since file I/O will be the bottleneck in this program.

If you don't know n in advance, you would still have to realloc in case you end up reading more than n rows. So a third option would be to use a linked list, which is probably the worst option since it is slow and adds complexity. The only advantage being that a link list allows you to swiftly add/remove rows on the fly.

Upvotes: 1

Related Questions