Falxmen
Falxmen

Reputation: 3

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

Upvotes: 0

Views: 64

Answers (4)

codebender
codebender

Reputation: 78

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

Upvotes: 0

Abhineet
Abhineet

Reputation: 5399

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];
};

Upvotes: 0

user3181531
user3181531

Reputation: 9

One way may be like this:

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

Upvotes: -1

Barmar
Barmar

Reputation: 781320

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

char order[27];

Upvotes: 3

Related Questions