pointer and memory question

J

Janice

int* ptr;
int i;
fread(&i,sizeof(int),0L,fs);
fread(ptr,sizeof(int),0L,fs);

Which way of declaring the buffer for the fread is better?
Thanx
 
R

Richard Heathfield

Janice said:
int* ptr;
int i;
fread(&i,sizeof(int),0L,fs);
fread(ptr,sizeof(int),0L,fs);

Which way of declaring the buffer for the fread is better?

Well, the first one is more likely to work. You can fix the second one like
this:

ptr = &i;

I suggest:

fread(&i, sizeof i, 1, fs);

Please note that a 0 for the third argument isn't going to read very many
objects, no matter how often you do it.
 
A

Alexei A. Frounze

Richard Heathfield said:
Well, the first one is more likely to work. You can fix the second one like
this:

ptr = &i;

I suggest:

fread(&i, sizeof i, 1, fs);

Please note that a 0 for the third argument isn't going to read very many
objects, no matter how often you do it.

I'd also note that the data stored in the file that you're reading with this
fread is not portable among different platforms.
That's for endianness and sizeof(int) reasons.

Alex
 
M

Malcolm

Janice said:
int* ptr;
int i;
fread(&i,sizeof(int),0L,fs);
fread(ptr,sizeof(int),0L,fs);

Which way of declaring the buffer for the fread is better?
ptr needs to point to some memory.

Generally you don't want to fread / fwrite a single int. It is not portable,
and almost always it is better to reconstruct the integer from a stream.
 
C

Cong Wang

Alexei said:
I'd also note that the data stored in the file that you're reading with this
fread is not portable among different platforms.
That's for endianness and sizeof(int) reasons.

Alex

I agree with Richard Heathfield.
Try POSIX function--read() instead.:)
 
R

Richard Heathfield

Cong said:
I agree with Richard Heathfield.
Try POSIX function--read() instead.:)

But I don't agree with you, I'm afraid. What he needs to do can almost
certainly be done with fread(), which has the advantage over read() that it
does not require a POSIX-conforming implementation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,166
Messages
2,570,907
Members
47,448
Latest member
DeanaQ4445

Latest Threads

Top