简体   繁体   中英

Size of variables char into a structure (C ANSI)

I have the following code

#include <stdio.h>
#include <string.h>

struct Wdd
    {
        char protocolId[4];
        char messageId[4];
        char sizeBody[4];
    };

main()
{

    struct Wdd msgWdd;

    strcpy(msgWdd.protocolId, "GABC");
    strcpy(msgWdd.messageId, "WDSS");
    strcpy(msgWdd.sizeBody, "0020");

    printf("protocolId: %s\n", msgWdd.protocolId);
    printf("messageId: %s\n", msgWdd.messageId);
    printf("sizeBody: %s\n", msgWdd.sizeBody);
    printf("sizeStructure: %d\n", sizeof(msgWdd));
}

The result of the print is

protocolId: GABCWDSS0020
messageId: WDSS0020
sizeBody: 0020
sizeStructure: 12

WHY? If I change the size of the fields for '5', the print is (correct, like I expected)

protocolId: GABC
messageId: WDSS
sizeBody: 0020
sizeStructure: 15

Why?

I've read the compiler pad some bytes to alignment requirements, but I couldn't really understand it. To fix this should I just increase the size of the fields (to 5) or is there another way around?

Alex

The null characters need a fifth byte. Otherwise, the null character is written at the same offset where the next field starts, and copying a string to the next field effectively overwrites the last null character. Printing out the strings simply involves looping over each character, until \\0 is found.

The char type has the least strict alignment requirements, that is, it can be located at any address, so the compiler doesn't insert any padding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM