简体   繁体   English

初始化2D struct char数组的正确方法

[英]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. 转子[0] [0] .order末尾的额外Q来自转子[0] [0]。缺口。 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. 您没有在order字符串末尾留空以留出结尾的null。 It should be 它应该是

char order[27];

You have written on all 26 bytes, leaving no space for terminating '\\0' char, hence, provoking Undefined Behavior . 您已经写了全部26个字节,没有空格来终止'\\0' 0'char,因此引发了Undefined Behavior With 27 chars array , you will get your desired output. 使用27个字符的数组 ,您将获得所需的输出。 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: 这是一个内存对齐问题,您尚未声明足够的空间来使订单数组以null终止,以修复此特定代码:

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. 如果您对为什么会发生这种情况感到好奇,则可以使用struct中的结构来解决它,尽管这是因为缺口变量地址紧随其后,然后printf找到了空终止符。

ref: https://en.wikipedia.org/wiki/Data_structure_alignment 参考: 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" }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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