0

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

user2864772
  • 53
  • 1
  • 4
  • 12
  • 3
    I don't understand the format of the file. You say (x, y) coordinates, but lines have different amounts of digits – salezica Dec 14 '13 at 13:49
  • The `calloc` function returns a pointer to some allocated memory, but `Trikamp` is not declared a pointer. Use the `struct Trikampiai *Trikamp;` declaration instead, which is commented out. The you need to use `Trikamp->stuff` instead of `Trikamp.stuff`. The return type of `main` should be `int`, not `void`. You code indentation is a bit weird, also. –  Dec 14 '13 at 13:52

2 Answers2

1

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?

Community
  • 1
  • 1
sherrellbc
  • 4,650
  • 9
  • 48
  • 77
1

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.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51