Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1019
  • Last Modified:

Dynamic arrays and Blockread

I'm trying to read a section of a file into a dynamically allocated array of byte.

My code looks like this

var
   temp : array of byte;
    fp : file of byte;

begin
   Assignfile(fp,"file.bin");
   Reset(fp);
   Setlength(temp,14);
   Blockread(fp,temp,14)
end;

The code compiles, and blockread thinks it's written 14 bytes, but when I look at temp[n] there's nothing there. When I replace temp with a fixed size array ( as in temp : array[0..13] of byte) everything works fine...

What's going on? And more importantly, how do I fix it?

cheers,

Adam...
0
AJFleming
Asked:
AJFleming
1 Solution
 
EpsylonCommented:
Try FileRead instead of BlockRead...
0
 
edeyCommented:
or PByteArray instead or array of byte?

GL
Mike
0
 
EpsylonCommented:
This is it!

BlockRead(fp,temp[0],14);
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
PeterLarsenCommented:
I agree with Epsylon.
Epsylon points to the first char (byte) in the stream. PByteArray would do the same.
0
 
AJFlemingAuthor Commented:
OK, well it works... Now, for an A grade, (which I've already given,) care to tell me why?

My assumption is that dynamic arrays in Delphi work differently to arrays in C... Thus, whereas

 fred[0] == fred in C
 fred[0] <> fred in Delphi...

Correct? If so, can anyone give me a convincing explaination at to why?

cheers for the quick response,

Adam...
0
 
EpsylonCommented:
The different between the declarations

   temp1: array of byte;
   temp2: array[0..13] of byte;

is that temp1 is a pointer to a buffer (after calling SetLength of course) and temp2 is an array on its own.

Note this too:

sizeof(temp1) returns 4 no matter what size the dynamic array has
sizeof(temp2) returns 14


To pass these arrays as buffer you can add [0] after the name.

Blockread(fp,temp1,14) passed the pointer to the function so it will fail
Blockread(fp,temp1[0],14) passed the address of the first byte of the array
Blockread(fp,temp2,14) passes the address of the array
Blockread(fp,temp2[0],14) passes the address of the first byte of the array which is the same as the address of the array
0
 
EpsylonCommented:
Small correction:

Blockread(fp,temp1,14) passed the address of the pointer so it will fail
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now