Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created January 13, 2017 21:11
Show Gist options
  • Save sachintha81/22ba7946f419601cc815cec2f4ce9f4d to your computer and use it in GitHub Desktop.
Save sachintha81/22ba7946f419601cc815cec2f4ce9f4d to your computer and use it in GitHub Desktop.
Reading a Text File into a 2D Array in C
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
// Allocate memory for the array like this:
int** array;
array = malloc(n * sizeof(*array)); /* Assuming `n` is the number of rows */
if(!array) /* If `malloc` failed */
{
fputs(stderr, ""Error allocating memory; Bailing out!"");
exit(-1);
}
int count = 1;
for(int i = 0; i < n; i++)
{
array[i] = malloc(count * sizeof(**array));
if(!array[i]) /* If `malloc` failed */
{
for(int j = 0; j < i; j++) /* free previously allocated memory */
{
free(array[j]);
}
free(array);
fputs(stderr, ""Error allocating memory; Bailing out!"");
exit(-1);
}
count++;
}
// Then, read data from the file into the array by using:
FILE* fp = fopen(""file.txt"", ""r"");
if(!fp)
{
for(int i = 0; i < n; i++) /* free previously allocated memory */
{
free(array[i]);
}
free(array);
fputs(stderr, ""Error opening 'file.txt'; Bailing out!"");
exit(-1);
}
int max = 1;
for(int i = 0; i < n; i++)
{
for(count = 0; count < max; count++)
{
fscanf(fp, ""%d"", &array[i][count]);
}
max++;
}
// Then print the results:
max = 1;
for(int i = 0; i < n; i++)
{
for(count = 0; count < max; count++)
{
printf(""array[%d][%d] = %d"", i, count, array[i][count]);
}
max++;
}
// And finally, free the allocated memory:
for(int i = 0; i < n; i++)
{
free(array[i]);
}
free(array);
}
@sachintha81
Copy link
Author

sachintha81 commented Jan 13, 2017

PROBLEM STATEMENT

I have a text file that looks like the following.

5
2 7
3 4 2

Basically, row 1 has 1 element, row 2 has 2 elements, row 3 has 3 elements, ... up to n rows with n elements.

I need to read them, and put into a 2-d array in this fashion:

a[0][0] = 5
a[1][0] = 2
a[1][1] = 7
a[2][0] = 3
a[2][1] = 4
a[2][2] = 2
...

You get the drift.

However I know n (the number of rows) only at run time. How would I go about reading the file into a 2x2 array?

StackOverflow post:
http://stackoverflow.com/questions/33579813/reading-a-text-file-into-a-two-dimentional-array-in-c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment