4

Let's say I have this declaration:

TYPE
 RDisk= packed record
   R2: array[1..1024] of Byte;
   etc
   etc
  end;

How do I initialize R2 to zero using a constant declaration like this:

CONST
 Disk: RDisk= 
   (
    R: ??
   );

This is related to Record in record (Cannot initialize)

Community
  • 1
  • 1
Gabriel
  • 20,797
  • 27
  • 159
  • 293
  • 1
    Type declarations use `=`, not `:`. Is that a type or a variable declaration? In your previous question, you made it sound like that was supposed to be a field of a record. Please clarify. – Rob Kennedy Jul 12 '11 at 16:56
  • Sorry. I have updated the question. – Gabriel Jul 12 '11 at 17:22

3 Answers3

4

Omit the fields you want to zero:

type
 RDisk= packed record
   R2: array[1..512] of Byte;
   I: Integer;
   D: Double;
   R3: array[1..512] of Byte;
  end;

const
 Disk: RDisk=
   (
    I: 3;
    D: 2.5;
   );

or,

const
 Disk: RDisk=
   (
   );


I don't know why it works, it doesn't quite fit in Record Constants' documentation.

Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • 1
    Thanks. It works. I just hope it isn't a 'hack' that will not work anymore in future versions of Delphi. – Gabriel Jul 12 '11 at 18:24
3

You can initialize an array with zero using this

ZeroMemory(@R2[0],length(R2));

or this

FillChar(R2[0],length(R2),0); 
opc0de
  • 11,557
  • 14
  • 94
  • 187
  • 2
    Why would FillChar be unsafe? Just FillChar the array, not the entire record, and it is fully safe. FillChar is only unsafe for types that are not "blittable", i.e. types that require special handling, like strings, interfaces, variants, etc. – Rudy Velthuis Jul 13 '11 at 15:27
  • Yep i perfectly agree with rudy – opc0de Jul 13 '11 at 16:46
  • 4
    Use of FillChar is unsafe because it's too easy to make mistakes. What if I use it on an array of records with no strings ("safe"), and then the next programmer adds a string to the record? Additionally, there's the easy mistake of confusing length() with SizeOf(). – Guy Gordon Jul 13 '12 at 13:55
  • @RudyVelthuis - See comment from GuyGordon. That's why :) :) :) – Gabriel May 04 '16 at 11:52
  • 1
    You can make mistakes in almost every line of code. Not really a good reason not to use a low level procedure. FillChar is no more unsafe than ZeroMemory. – Rudy Velthuis May 05 '16 at 02:08
3

You can declare a constant of type R2 and initialize it to all zeros like this:

const
  zeros: R2 = (0, 0, 0, ...);

The array length is 1024, so you must specify all 1024 comma-separated values in that list.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467