C - arrays, reading from file to struct array (calloc realloc free...)

485 views Asked by At

I fail in first steps of my program. First of all i need to read from file into a struct array. I fail at doing that - i get lots of errors and i got a feeling that my syntax in reading is not right at Once I do this i will be able to carry on with my program. I think that I have to use calloc / realloc / free and all of those strange thing because my data file might have very long set of digits.

My data file:

4 5 5 6
9
5 7 6 9
6 5
1 8 1 2 3 6 5
1 9
4 5 5 6
9
5 7 6 9
6 5
1 8 1 2 3 6 5
1 9

it has to be read like coordinates (x ; y) - doesn't matter how these numbers are placed - i can/must jump and read

2

There are 2 answers

0
sherrellbc On

Your use of calloc is not correct. As Herman has stated in his comment, calling calloc returns a pointer to the block of memory sizeof(struct Trikampiai) bytes long; you are storing a pointer in an int. Also, you never use the character array buf.

Try: struct Trikampiai *Trikamp = calloc(1, dydis); if you want to dynamically allocate the memory, or just keep struct Trikampiai Trikamp; if you want automatic allocation. From what I can tell of your program's intention you are confusing these two concepts of memory allocation (stack vs heap). This is a good resource: What and where are the stack and heap?

i.e.

Trikamp->xas = sk; vs Trikamp.xas = sk

With the former you have to access the structure by using the -> operator, while the latter requires the . operator, which is what I think you are wanting.

What other errors are you seeing?

0
Lutz Lehmann On

You need a length and a counting index. Both can be set to zero in the beginning. In the loop, if length is equal to the counting index, you increase length by some reasonable amount, not too small, not too large, and call realloc on the trikamp array using the increased length

if(count==length) {
    length += delta;
    trikamp = (struct Trikampiai *)realloc(trikamp, dydis*length);
}

You can access the field of the structure as (trikamp+count)->xas or equivalently as trikamp[count].xas, the compiler sees both as the same.