Why not writing all of the fields?! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why not writing all of the fields?!

I was learning about files in C and saw this code struct foo{ char x,y,z; }; int main(){ FILE *f=fopen("D:/f.bin", "wb"); struct foo bar; bar.x='t'; fwrite(&bar, sizeof(bar), 1, f); } it was mentioned that the value for y and z won't be stored in the file. and that's what actually happened when I tried it. I want to learn more about this but i couldn't find anything helpful. can you explain how this work, is it a compile-time or a run-time process, is there any other similar cases, is this just limited to structures?

23rd May 2018, 11:27 PM
omar alhelo
omar alhelo - avatar
5 Answers
+ 1
Could it be that y and z are not written because they are empty? What are exact contents of your output file?
24th May 2018, 3:13 AM
BlazingMagpie
BlazingMagpie - avatar
+ 2
Are you sure that you didn’t just overlook a few zeros or something in the file? Did you look at it with an hex editor?maybe the character got written but are not displayable? This is not expected behavior as far as I know Nope that shouldn’t happen. https://code.sololearn.com/c6EBvTcrz5jV/?ref=app incomplete initialization doesn’t change the size of the struct and we are writing everything between &bar and &bar+sizeof(bar) to the file. There should be random stuff in there
23rd May 2018, 11:42 PM
Max
Max - avatar
+ 1
Some more questions: What compiler did you use which compiler flags, which os are you on ? Have you tried disassembling the executable and looking at what’s going on ?
24th May 2018, 12:15 AM
Max
Max - avatar
0
@Max thanx for replying. Yes, I'm sure there's only the value of x in the file, I've even tried assigning a value for y, and again only x and y values were stored but not z. I'm running MinGw on windows, I'm running it from Code::blocks IDE, so I don't think there are any special flags. I'll install Cygwin and try testing it on GCC. however, I don't think it would make a difference. And about the disassembling thing, I don't think I'll understand what would be written. I'm still a noob 😅😅 UPDATE: Same on GCC.. only assigned variables are stored.
24th May 2018, 2:18 AM
omar alhelo
omar alhelo - avatar
0
@BlazingMagpie Yup, that's it. local struct-type variables are initialized to zero by default. I tried it using malloc and the unassigned variables were stored with random values. @Max that makes you right, there should be some zeros in the file, but it didn't occur to me because I was opening it using notepad. How stupid 🤦‍♂️
24th May 2018, 3:55 AM
omar alhelo
omar alhelo - avatar