Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In your code, <code>char * filename;</code> is a pointer to a char. This means that <code>filename</code> only occupies 4 bytes. Even if your string is 1000 bytes long, since <code>filename</code> is simply a pointer, it just contains the 4-byte memory address of the first character of your string.</p> <p>So you have two solutions: use <code>char filename[MAX_LENGTH]</code> to declare a string of size <code>MAX_LENGTH</code> and always pass that. Or, you can include another field, say, "filename_length", which tells you how many bytes to expect when you read the filename field.</p> <p>(The above is actually false. <code>filename</code> may not be 4 bytes long. filename will be <code>sizeof(char*)</code> bytes long. This is probably 4 bytes on your computer. But pointers are not always 4 bytes, and nowadays people are getting into a lot of trouble for assuming a 4-byte pointer on 64-bit architectures. So I'm just sayin'. Don't downvote me.)</p> <p>To answer your second question - why is sizeof() 20 bytes? The compiler will pad pieces of the struct with extra bytes so that each member fits inside a 4-byte boundary. The compiler can work efficiently with "words" rather than weird-sized structures. (Again, the "4" just depends on the architecture. Each architecture has its own "word" length.) This known as alignment. There is an excellent SO thread which gives more detail: <a href="https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member">Why isn&#39;t sizeof for a struct equal to the sum of sizeof of each member?</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload