Mystery in C | SoloLearn: Learn to code for FREE!


Mystery in C

Can anyone experienced in C please give a little bit of explanation about what happens in this code i got from an old book? I just can't get my head around the thing.


11/5/2018 12:49:23 PM


7 Answers

New Answer


If you write "Hello, world!" then the memory would be the same as those 'weird looking' numbers. Lets take the first number for example and remove the 0x: 6c6c6548 The ascii values for H = 48, e = 65, l = 6c, see a pattern yet? The first 4 numbers are stored in little endian, which basically reverses the bytes when stored in memory and the other 4 numbers uses big endian. This would allow the program to work on both architectures ( assuming the #define was correct ). A union stores its member variables at the same memory location. If cipher changes value, so does what. The only difference though, is that the underlying bytes are interpreted differently. It's also important that both types have the same size. Each cipher is assigned a number, after assigning, the memory looks like this ( remember that the bytes get switched around ): 48 65 6C 6C 6F 2C 20 77 6F 72 6C 64 21 0A 00 00 what interprets it as a char array ( so it reads 1 byte at a time ), now grab as a reference and see that each byte corresponds to a character, which is the output.


@Dennis i was finishing mine explanation to send. But yours is just perfect


Note, I posted a byte order detection fix (for gcc on SoloLearn) in the code comments.


@Ricci Hardiansyah Raynaldhi If you need help please post a new and detailed question in the Q&A section and someone who has knowledge about it will answer. Changing topic here is not appropriate.


aha, long is 4 bytes, char is 1 byte. hence initialization of cypher[4] and what[16]. So, when 6c6c6548 is assigned to cypher[0], 6c is assigned to what[0] and so on... This is such a satisfying code once you see it :) Thanks a lot for clearing that out @Dennis



can you tell me about "array"?