Reputation: 23
type
TS = record
FN, RN: String;
end;
var
Sy: array of TS;
S: ^String;
...
SetLength(Sy,2);
begin
Sy[0].FN:='123';
Sy[0].RN:='bad';
Sy[1].FN:='345';
Sy[1].RN:='000';
end;
...
S := @(Sy [i].FN);
How to imitate Pascal logic in C language? Next code does not work:
typedef struct
{
char FN[256];//char FN[] /*isn't allowed by compiler*/
char RN[256];//char RN[] /*isn't allowed by compiler*/
} TS;
TS Sy[];
main()
{
Sy=malloc(2*sizeof(TS));
strcpy(Sy[1].FN,"1234");
}
QUESTION 1
I get compiler error error C2106: '=' : left operand must be l-value
. What should I do to imitate Pascal logic in case of SetLength?
QUESTION 2
How to specify a string of unknown size (Ansistrings is Pascal). When I set char FN[];
I get error error C2229: struct '<unnamed-tag>' has an illegal zero-sized array
. What should I do to imitate Pascal logic in case of Ansistring?
Upvotes: 0
Views: 650
Reputation: 63
Question 1:
malloc() returns a void pointer (void*), so I think Sy would need to be a pointer type. The most direct way would be changing TS Sy[]
to TS *Sy
. Then when using malloc you will need to cast the pointer to a TS pointer, like so:
Sy = (TS*)malloc(2*sizeof(TS));
Question 2:
As far as I'm aware, the only suitable type that would work would be a c-string. In which case the solution is similar to that in question one, change FN[]
and RN[]
to *FN
and *RN
. I'm not very experienced with C however, and that may not be the most efficient way to handle things, especially since then I believe the struct will not take up a contiguous memory space. Another problem with this is you will still need to specify the size of the c-string at some point, but you will be able to do it dynamically, rather than at compile time.
(Edit) As a side note, you should also use free() to free the memory allocated by malloc when you're done with it.
Upvotes: 0