结构中的C访问元素
我在用C写程序时遇到了麻烦。 我定义了一个结构:结构中的C访问元素,c,struct,C,Struct,我在用C写程序时遇到了麻烦。 我定义了一个结构: typedef struct { char* alphabet; /* Defines the supported characters by the encryption algorithm */ char* symbols; /* Defines the symbols used to encrypt a message */ char* dictio
typedef struct {
char* alphabet; /* Defines the supported characters by the encryption algorithm */
char* symbols; /* Defines the symbols used to encrypt a message */
char* dictionary; /* Defines the translation for all characters defined in alphabet */
char* transposition; /* Defines the transposition key used in the second encryption step */
} adfgx_machine;
adfgx_machine* am_create(char* alphabet, char* symbols, char* dictionary, char* transposition) {
adfgx_machine machine;
if(strlen(alphabet)*2!=strlen(dictionary)){
printf("s", "Het aantal karakters in de dictionary moet dubbel zoveel zijn als het antal karakters in alphabet!");
exit(1);
}
machine.alphabet=alphabet;
machine.symbols=symbols;
machine.dictionary=dictionary;
machine.transposition=transposition;
return &machine;
}
我还创建了一个方法来创建此结构的实例:
typedef struct {
char* alphabet; /* Defines the supported characters by the encryption algorithm */
char* symbols; /* Defines the symbols used to encrypt a message */
char* dictionary; /* Defines the translation for all characters defined in alphabet */
char* transposition; /* Defines the transposition key used in the second encryption step */
} adfgx_machine;
adfgx_machine* am_create(char* alphabet, char* symbols, char* dictionary, char* transposition) {
adfgx_machine machine;
if(strlen(alphabet)*2!=strlen(dictionary)){
printf("s", "Het aantal karakters in de dictionary moet dubbel zoveel zijn als het antal karakters in alphabet!");
exit(1);
}
machine.alphabet=alphabet;
machine.symbols=symbols;
machine.dictionary=dictionary;
machine.transposition=transposition;
return &machine;
}
现在我正在尝试打印结构的字母表,如果给定这样的结构,但是我的程序总是崩溃。我已经尝试过[dot]运算符,但该运算符也不起作用。这是我的密码:
void am_create_dictionary(adfgx_machine* am) {
printf("%s",am->alphabet);
}
这是我的主要方法:
int main(int argc, char* argv []) {
adfgx_machine* mach = am_create("azert","azert","azertazert","azert");
am_create_dictionary(mach);
return 0;
}
所以,如果我用am.alphabet替换am->alphabet,它也不起作用。我做错了什么
更新:
如果我不使用我的方法,而是直接在主方法中打印它,它确实有效?!因此,我的主要方法是:
int main(int argc, char* argv []) {
adfgx_machine* mach = am_create("azert","azert","azertazert","azert");
printf("%s",mach->alphabet);
return 0;
}
您正在创建结构变量adfgx_machine;在函数am_create内部,因此它成为该函数的局部变量。而且,当函数退出时,它的所有局部变量和机器都将被销毁
为了实现您想要的,您可以使用malloc或calloc动态地为变量机器分配内存。主要问题是在堆栈上分配返回值。它很可能会被覆盖。你最好使用malloc
这个问题有大量的重复。