Recent

Author Topic: Have anyone know how to translate C 0-length array to Pascal array?  (Read 11889 times)

VisualLab

  • Hero Member
  • *****
  • Posts: 646
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #15 on: April 12, 2024, 12:31:05 pm »
In the case of C, when working with flexible arrays (in C),
The statement above is problematic (strictly speaking, it is incorrect.)  identifer[0]; is _not_ a flexible array member.  A flexible array member is a declaration _without_ the element count, i.e, identifier[];

Declaring a zero sized array in C, i.e, identifier[0] was one of those "implementation dependent" "items" in the language and not all compilers treated it the same way (particularly pre-C standardization.)

Actually. Seemingly similar, but slightly different.

I'm not sure there's anything in Pascal that would enable this behavior.
Unfortunately, there is no way in Pascal to emulate C's flexible array member exactly.

In principle, emulation can be done using pointers. Not very elegant and made for mistakes. But the C solution isn't much better and is also error prone. Because it also involves "juggling" pointers.

A separate issue is whether Pascal really needs such structures (i.e. flexible arrays). Maybe just to be able to handle the shitty solutions present in C, but is it worth breaking the compiler?
_Any_ language that is suited for low level programming should have that ability.  Unfortunately, Pascal does not.

Hmmm... This is a half-baked solution, a nasty makeshift solution naively pretending to be a decent solution. It's better to use pointers explicitly. At least we know what is happening in the code (and that we have to be careful with it, because it involves "juggling" pointers).

VisualLab

  • Hero Member
  • *****
  • Posts: 646
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #16 on: April 12, 2024, 12:41:46 pm »
_Any_ language that is suited for low level programming should have that ability.  Unfortunately, Pascal does not.

Please explain why.
Sure.

And just in case someone is wondering why the size of the empty record may be important.  In Windows and likely other operating systems, there are cases where the specific version/layout of a record is determined by its size.  Having an unwanted element in the array makes that method unavailable for records that have a flexible array member.

But such behavior is a classic hack. If it is known that a record may have different versions, a better solution would be to include a field informing about its version - an explicit field. In your own program, this is acceptable. But such a makeshift solution should not appear in a publicly available library or OS. I understand that in the 1960s and 1970s, every byte was saved. But in the 1990s it no longer made sense. Such "clever" tricks take their revenge after some time. In other words, it sounds like bad design (i.e., poorly designed software).

440bx

  • Hero Member
  • *****
  • Posts: 5188
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #17 on: April 12, 2024, 12:49:25 pm »
Hmmm... This is a half-baked solution, a nasty makeshift solution naively pretending to be a decent solution. It's better to use pointers explicitly. At least we know what is happening in the code (and that we have to be careful with it, because it involves "juggling" pointers).
I can't help being surprised by that attitude.

There is nothing "half-baked", "nasty" or pretending anything.  If a location in a program needs to be made accessible, declaring an identifier at that location is the _natural_ solution.  Anything else is half-baked.

if all that is needed is to identify a location then the language should not force the identifier to consume space.  This stuff is run of the mill, bread and butter stuff in Assembly programming and I am not aware of anyone ever claiming identifying locations in Assembly code is a "half baked" solution, a "nasty makeshift solution" or some other unflattering description of something that is as natural as declaring a variable.
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 12162
  • FPC developer.
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #18 on: April 12, 2024, 01:16:24 pm »
Because there are times when it is necessary to determine the address of a field in a record without being forced to affect the size of the original record.  That's one reason. 

So can you explain that then with two C definitions and their sizes. I seem to get the feeling that the alignment bytes are not counted in the sizeof, which I didn't know.

That doesn't mean that automatically validates the statement, since, like Leledumbo I've never needed such construct in 15 years of embedded C.  I only know it from FreeBSD and windows headers.

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 12162
  • FPC developer.
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #19 on: April 12, 2024, 01:18:45 pm »
I can't help being surprised by that attitude.

There is nothing "half-baked", "nasty" or pretending anything.  If a location in a program needs to be made accessible, declaring an identifier at that location is the _natural_ solution.  Anything else is half-baked.

Sure. But the need of stuffing it in the struct before it with a baroque construct, that is the question.

In freepascal you can afaik declare a record end; at an absolute address. It is tie in to the preceding record (presumably for alignment) and the practical uses of such construct that is being discussed.



440bx

  • Hero Member
  • *****
  • Posts: 5188
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #20 on: April 12, 2024, 02:03:16 pm »
So can you explain that then with two C definitions and their sizes. I seem to get the feeling that the alignment bytes are not counted in the sizeof, which I didn't know.
I just tried it in VS and, as expected, the alignment bytes are most definitely taken into account.  IOW, alignment bytes are added as necessary and counted as they should be.  I verified this in VS2022 just before typing this reply.

That doesn't mean that automatically validates the statement, since, like Leledumbo I've never needed such construct in 15 years of embedded C.  I only know it from FreeBSD and windows headers.
I cannot say anything about the way you or anyone else programs.  What I can say is that marking a location while taking into consideration any alignment requirements within a record without affecting the size of the record is definitely a useful feature, that said, it certainly isn't a feature that is very commonly needed.

As far as you or anyone else not needing the feature in 15 years or more, the fact that the feature has made it into the C99 standard and, was supported by multiple compilers before that, indicates that there are programmers who find it useful and use it (probably a bit more often than every 15 years.)

 
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

VisualLab

  • Hero Member
  • *****
  • Posts: 646
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #21 on: April 12, 2024, 03:10:53 pm »
if all that is needed is to identify a location then the language should not force the identifier to consume space.  This stuff is run of the mill, bread and butter stuff in Assembly programming and I am not aware of anyone ever claiming identifying locations in Assembly code is a "half baked" solution, a "nasty makeshift solution" or some other unflattering description of something that is as natural as declaring a variable.

Agreed about the assembler (especially if it is used for microcontrollers). As for the programming language, it is, to put it mildly, controversial.

Seenkao

  • Hero Member
  • *****
  • Posts: 687
    • New ZenGL.
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #22 on: April 12, 2024, 04:17:44 pm »
Я не понимаю почему вы просто не укажите человеку использовать динамические массивы? Много текста, а решения нет?

Создайте динамический массив, в нужный момент определяйте его длину и не забудьте при закрытии программы уничтожать ваш массив. Всё, проблема решена.


Google translate:
I don't understand why you don't just tell the person to use dynamic arrays? Lots of text, but no solution?

Create a dynamic array, determine its length at the right time, and do not forget to destroy your array when closing the program. That's it, problem solved.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

440bx

  • Hero Member
  • *****
  • Posts: 5188
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #23 on: April 12, 2024, 04:29:59 pm »
Google translate:
I don't understand why you don't just tell the person to use dynamic arrays? Lots of text, but no solution?

Create a dynamic array, determine its length at the right time, and do not forget to destroy your array when closing the program. That's it, problem solved.
Problem is not solved at all.

The problem consists of marking within a record the start of an array.  Specifically, this array:
Code: C  [Select][+][-]
  1.      struct multiboot_color framebuffer_palette[0];
Pascal has no exact equivalent. 

In Pascal, the field could be translated as:
Code: Pascal  [Select][+][-]
  1. framebuffer_palette : array[0..0] of multiboot_color;
but, that definition has a problem, which is, it consumes space therefore the size of the Pascal definition will _not_ match the size of the C definition and, that, can be a real problem depending on how the code uses the record definition.
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

Seenkao

  • Hero Member
  • *****
  • Posts: 687
    • New ZenGL.
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #24 on: April 12, 2024, 04:58:17 pm »
Достаточно понять, что в Паскале этого делать не нужно. Не надо делать те вещи, которые предлагают другие языки программирования, особенно, если оно очень не подходят для Паскаля.
Достаточно создать структуру (уже создана?) и сделать на её основе динамический массив. В нужный момент просто либо ставить указатель на элемент, либо просто брать элемент массива.

Да, работы будет больше, но конечный результат будет такой же.

Да, мы можем сделать практически то же самое что в C, но работы всё равно будет больше (если конечно уже не готовы решения). Всё равно придётся выделать память, а по закрытию программы обязательно освобождать её.

-----------------------------------------------
Google translate:
It’s enough to understand that you don’t need to do this in Pascal. There is no need to do those things that other programming languages offer, especially if it is very unsuitable for Pascal.
It is enough to create a structure (already created?) and make a dynamic array based on it. At the right time, you can simply either put a pointer to an element, or simply take an element of the array.

Yes, there will be more work, but the end result will be the same.

Yes, we can do almost the same thing as in C, but there will still be more work (unless, of course, solutions are already ready). You still have to allocate memory, and after closing the program, you must free the memory.
Code: Pascal  [Select][+][-]
  1. framebuffer_palette : array of multiboot_color;
Code: Pascal  [Select][+][-]
  1. ...
  2. // create
  3.   SetLength(framebuffer_palette, len_multiboot_color);
  4. // Use the following code if the structure is complex.
  5.   for i := 0 to len_multiboot_color - 1 do
  6.     GetMem(pointer(framebuffer_palette[i]), SizeOf(multiboot_color));
Code: Pascal  [Select][+][-]
  1. ...
  2. // destroy
  3.  
  4. // Use the following code if the structure is complex.
  5.   for i := 0 to len_multiboot_color - 1 do
  6.   begin
  7.     FreeMem(framebuffer_palette[i]);
  8.     framebuffer_palette[i] := nil;    
  9.   end;
  10.  
  11. // required code
  12.   SetLength(framebuffer_palette, 0);
  13. ...
  14.  
Yes, for beginners it is not entirely easy. But if necessary, then it’s enough just to remember what to do.

Rus:
Да, для новичков это не совсем просто. Но если надо, то достаточно просто запомнить что надо делать.

Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

440bx

  • Hero Member
  • *****
  • Posts: 5188
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #25 on: April 12, 2024, 05:21:10 pm »
It’s enough to understand that you don’t need to do this in Pascal. There is no need to do those things that other programming languages offer, especially if it is very unsuitable for Pascal.
Yes, you do need to do this in Pascal.

The reason is very simple: the bulk of important code that Pascal has to interface with is written in either C or C++.  When Pascal cannot match a C or C++ declaration, that's a problem, a real problem because Pascal's inability to handle these constructs makes it unsuitable or, at the very least inconvenient, in the situations where they are used.  The last thing the Pascal language needs is to be exposed as unsuitable (or inconvenient) in some cases.

Let's not forget that the world is mostly C and C++ centric, a language that cannot or does not adapt to the C/C++ world does not have a bright future.

What's really unfortunate is that flexible arrays is an easy feature to implement in a compiler but, it looks like that if the feature exists in C then its inclusion in Pascal will immediately be shot down. 

The people involved in the development of language standards, in this case C99, know a little something about compiler design.
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

Thaddy

  • Hero Member
  • *****
  • Posts: 16832
  • Ceterum censeo Trump esse delendam
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #26 on: April 12, 2024, 06:22:14 pm »
I still don't see the point that anything is missing from C that can not be expressed in Pascal. That is simply a fallacy. iow a blatant lie. (and I don't mean macro's)
C, any version, is basically a simplistic way to run over pointers, nothing more.
And if so required, Pascal can do just that too.... >:D in all cases.

The original question was already answered and works.
« Last Edit: April 12, 2024, 06:44:19 pm by Thaddy »
Changing servers. thaddy.com may be temporary unreachable but restored when the domain name transfer is done.

440bx

  • Hero Member
  • *****
  • Posts: 5188
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #27 on: April 12, 2024, 08:45:27 pm »
I still don't see the point that anything is missing from C that can not be expressed in Pascal. That is simply a fallacy. iow a blatant lie. (and I don't mean macro's)
Simply no, what you stated there is simply not true.

The structure definition shown by the OP _cannot_ be expressed in Pascal.  No way around it, it simply cannot.  There is no way for Pascal to guarantee the field's alignment will be as in C without having the compiler reserve space for the field.  Therefore, either the alignment may be incorrect or the record size will be incorrect.  There is no way for Pascal to guarantee they will _both_ be correct.

That there are workarounds in this case ?.... yes, there are, but they all are a pain in the neck, definitely inconvenient and definitely error prone.  IOW, definitely undesirable.

That's far from the only thing Pascal cannot do that C can.  For instance, I don't know of any way to tell the Pascal compiler to align a record field on a 64 bit or 128 bit boundary. 

There is no way for the Pascal compiler to put a class on the stack.  Whether you like it or not, they all go on the heap  which means allocation and deallocation must be done manually.

Those are just a few off the top of my head.  There are more but the above makes the point, there _are_ things missing in Pascal.  That's particularly obvious, not to mention a real pain, when porting C code to Pascal.
(FPC v3.0.4 and Lazarus 1.8.2) or (FPC v3.2.2 and Lazarus v3.2) on Windows 7 SP1 64bit.

Thaddy

  • Hero Member
  • *****
  • Posts: 16832
  • Ceterum censeo Trump esse delendam
Re: Have anyone know how to translate C 0-length array to Pascal array?
« Reply #28 on: April 12, 2024, 09:12:53 pm »
Of course it can! The alignment is btw different for different C compilers. I will write definite proof that anything a GNU C compiler can do can be done in Pascal. And you should know that! >:D
But that is not relevant to the question. That should be solved.
Changing servers. thaddy.com may be temporary unreachable but restored when the domain name transfer is done.

Kays

  • Hero Member
  • *****
  • Posts: 614
  • Whasup!?
    • KaiBurghardt.de
Re: Have anyone know how to translate C 0‑length array to Pascal array?
« Reply #29 on: April 13, 2024, 10:46:28 am »
If I understand correctly, this is a length‑prefixed array. A length‑prefixed array can be achieved with schema data types. Schemata are defined by ISO standard 10206 “Extended Pascal”. Unfortunately the FPC does not support EP, in particular schemata, yet.
Code: Pascal  [Select][+][-]
  1. type
  2.         integerList(length: integer) = array[1..length] of integer;
  3. var
  4.         myList: integerList(5); { = array[1..5] of integer }
  5. begin
  6.         writeLn(myList.length); { writes `5` }
You need to use pointers if the length changes at run‑time; Extended Pascal also permits variable sub‑range boundaries, e. g. the following is legal:
Code: Pascal  [Select][+][-]
  1. program variableSubRangeDemo;
  2.         procedure p(protected length: integer);
  3.                 type
  4.                         arrayIndex = 1..length;
  5.                 var
  6.                         myArray: array[arrayIndex] of integer;
  7.                         i: arrayIndex;
  8.                 begin
  9.                         { Now you have an array[1..5] of integer
  10.                           without using pointers or schema data types. }
  11.                 end;
  12.         begin
  13.                 p(5);
  14.         end.
Again, it is not necessary to invent novel syntax, this feature is not missing in Pascal, it merely lacks FPC support.
Yours Sincerely
Kai Burghardt

 

TinyPortal © 2005-2018