How do i determine the size of an array from a character read from a file?

90 views Asked by At

I have to allocate a dynamic array and i know how many columns there will be on the array but i don't know how many rows, all i have is a number on a .txt file. I have tried the following code but i am not sure it will work:

int x = (int)fgetc(file)-48;

Since the ascii value of 0 is 48, i assumned that i needed to cast the character read from the file in order to be able to use it as my rows number.

I assume i should be able to allocate the array the 2D array as it follows:

m = (int **)malloc(x*sizeof(int*));
for (i=0;i<x;i++)
{
    m[i] = (int*)malloc(10*sizeof(int));
}

Am i correct? Any help will be highly apretiated.

3

There are 3 answers

0
drinking On

You can design a list and dynamically insert your rows.

3
Peter - Reinstate Monica On

Do I understand correctly that your file looks like

327            // number of lines
1 2 3          // line 1
33 44 55       // line 2 

... repeats until 327 lines have been printed, all with 3 elements? Note that the line breaks would be optional and could be any whitespace.

The canonical way to read a number from text in C is using scanf. scanf uses, like printf, a weird looking format string as the fist parameter. Each basic type has a letter associated with it, for integers it's d or, more intuitively, i. These letters are prefixed with a %. So to read an integer, you would write scanf("%d", &lines); if lines is an int holding the number of lines. (Do rather not use x, for readability).

The way you allocate your array is correct (provided x holds the number of lines and 10 is the known line length). One style issue is that the 10 should be #defined as a macro so that you can use e.g. malloc(LINE_LEN*sizeof(int)). That helps later when that number should ever change and you have (in a real world program) scattered references to m over several source files.

If this is just a little program and the array isnt't inordinately large and does not need to live longer than the function call (which, in the case of main(), may be long enough in any case), the easiest would be to use a variable size array in C; provided you use a modestly modern compiler:

#define LINE_LEN 10
int lineCount;
scanf("%d", &lineCount);
int m[lineCount][LINE_LEN];
// fill from file

If you compile with gcc you'll probably need to specify "-std=c99" as a command line option for that.

1
doctagre On

First off fgetc() returns an integer, so casting it as an int will do nothing. Second you're only reading in one integer at a time with fgetc() so you will have a 1 digit number in x.

Your array allocation looks correct, but you can also allocate the columns as an array of int * on the stack and then allocate the rows dynamically as m[i] = (int*)malloc(x*sizeof(int)); from i = 0->9