简体   繁体   中英

Correct way to initialize a 2D struct char array

The extra Q at the end of rotor[0][0].order is from rotor[0][0].notch. What is the cause of this and what should be done to avoid this concatenation?

#include <stdio.h>

struct rotor_wirings
{
    char order[26];
    char notch[2];
};
/* rotor[MODEL][ROTORNAME] */
struct rotor_wirings rotor[10][10] =
{
    /* Commercial Enigma A, B */
    {
        { "DMTWSILRUYQNKFEJCAZBPGXOHV", "Q" },
        { "HQZGPJTMOBLNCIFDYAWVEUSRKX", "E" }
    }
};

int main()
{
    printf("First rotor is: %s\n", rotor[0][0].order);
    return 0;
}

The output is:

First rotor is: DMTWSILRUYQNKFEJCAZBPGXOHVQ

You didn't leave room for the trailing null at the end of the order string. It should be

char order[27];

You have written on all 26 bytes, leaving no space for terminating '\\0' char, hence, provoking Undefined Behavior . With 27 chars array , you will get your desired output. Live Example

struct rotor_wirings
{
    char order[27]; // Extra byte for terminating '\0'
    char notch[2];
};

Its a memory alignment issue and you haven't declared enough space for your order array to be null terminated, to fix this specific code:

char order[27];

in the struct would fix it, if you're curious as to why this happened though it is because the notch variable address is aligned right after and printf found the null termination then.

ref: https://en.wikipedia.org/wiki/Data_structure_alignment

One way may be like this:

struct rotor_wirings rotor[10][10] =
{
    /* Commercial Enigma A, B */
    {
        { "DMTWSILRUYQNKFEJCAZBPGXOHVQ"},
        { "HQZGPJTMOBLNCIFDYAWVEUSRKXE" }
    }
};

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