将主数据转换为全局数据,以后由主数据库进行修改?

Yee*_*Kee 9 c arrays global-variables

我有两个字母数组,格式如下:

const char plain[26] = {'a','b',....'y','z'} // this is the the full alphabet
const char crypt[26] = {'i','d',....'m','x'}; // this is the the alphabet scrambled
Run Code Online (Sandbox Code Playgroud)

两个数组中的字母顺序可以根据输入而改变.此更改发生在main函数中.

这样做的目的是将字符串的字母与第二个字母匹配,就像加密一样.我将字符与数组值进行比较.所以它看起来像这样(简化)

text[3] = 'yes';
changed[3];
if(text[0] == plain[25]){    //would be done under a for loop so 25 would be a changing integer value
    changed[0] = [crypt[25];
}
Run Code Online (Sandbox Code Playgroud)

我的代码完全在main函数下工作.我想提到这样的目的,因为我之前的问题只是由于数组和格式的类型.由于数组被移到外面,我可能会再次遇到这些问题.


现在我想让数组全局化.实际加密发生在不将数组作为变量的函数中.但我希望该功能可以访问它们.

这就是它现在的样子

const char plain[26];
const char crypt[26];
int maint(void){
    const char plain[26] = {'a','b',....'y','z'} \\values get changed here 
    const char crypt[26] = {'i','d',....'m','x'} \\and here
Run Code Online (Sandbox Code Playgroud)

虽然这没有提供任何错误,但我没有得到输出,我相信其他功能正在使用空白数组而不是更改的数组(如果更改甚至有效).

我尝试过不同的数组类型,我相信问题在于初始化或给出数组值.

编辑:为了澄清,两个数组可以是任何顺序.一个文本文件随机化顺序可以给我的格式为:

b,r
m,o
l,s
...
...
...
Run Code Online (Sandbox Code Playgroud)

两种情况下,字母表都是随机的.在第一列对应于第一列(普通)的情况下,第二列将对应于第二列(crypt).

如果是一种通过collums读取并以格式存储的方式

plain ='bml ...'; \整个字母随机化crypt ='ros ...'; \整个字母随机

那也行.

Bla*_*aze 11

plaincrypt你有main不一样的全球性的.由于你再次声明它们,它们是新的,只能在其中可见main.因此,你不会改变全球的.

相反,只在全局声明它们并在main函数中进行赋值:

char plain[26];

int main(void) {
    memcpy(plain, "abcdefghijklmnopqrstuvwxyz", 26); //values get changed here
    return 0; // indicate successful program execution
}
Run Code Online (Sandbox Code Playgroud)

另请注意,有一些语法错误

const char plain[26] = {'a','b',....'y','z'} \\values get changed here 
Run Code Online (Sandbox Code Playgroud)

评论从//,而不是\\,你需要;一个声明后.此外,int main应该返回intC.

当然,如果您不需要实际更改内存并仅将其分配给预定义的字符集,则可以这样执行:

const char *plain;

int main(void) {
    plain = "abcdefghijklmnopqrstuvwxyz";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这样你仍然可以使用语法来读取它plain[5],但是你不能用它来分配它plain[5] = 'a';.

  • 谢谢,这很有效.但是,我确实需要更改数组中字母的顺序.我从文本文件中获取两个数组,它们可以按任何顺序排列.很抱歉语法错误,该代码只是一个示例,以显示我如何格式化它. (2认同)