CS50 / BEGINNER - C 中嵌套 for 循环中的分段错误

CS50 / BEGINNER - Segmentation fault in nested for loop in C

我正在尝试编写代码,从明文字符串输入中获取每个数字,如果是字母,则输出不同的字母,如替换键(26 个字母键)所定义。

换句话说,如果字母表是“abcd”并且提供的键是“hjkl”,输入“bad”将输出“jhl”。

// Regular alphabet is to be used as comparison base for key indexes //
string alphabet = "abcdefghijklmnopqrstuvwxyz";

// Prompt user for input and assign it to plaintext variable //
string plaintext = get_string("plaintext:  ");

非字母应按原样打印。

我的想法是通过字母表中的每个索引循环输入数字以查找相应的字母,如果找到,则从字符串中打印相同的索引字符。 (令人困惑,我认为)

这个循环,然而,returns当我运行它时出现段错误,但在调试时却没有:

// Loop will iterate through every ith digit in plaintext and operate the cipher //
for (int i = 0; plaintext[i] != '[=11=]'; i++) {
    // Storing plaintext digit in n and converting char to string //
    char n[2] = "";
    n[0] = plaintext[i];
    n[1] = '[=11=]';

    // If digit is alphabetic, operate cipher case-sensitive; if not, print as-is //
    if (isalpha(n) != 0) {
        for (int k = 0; alphabet[k] != '[=11=]'; k++) {
            char j[2] = "";
            j[0] = alphabet[k];
            j[1] = '[=11=]';

            if (n[0] == j[0] || n[0] == toupper(j[0])) {
                if (islower(n) != 0) {
                    printf("%c", key[k]);
                    break;
                } else {
                    printf("%c", key[k] + 32);
                    break;
                }
            }
        }
    } else {
        printf("%c", (char) n);
    }
}

怎么了?我在网上寻求帮助,但大多数资源对初学者来说不是很友好。

除了一个错误外,您的代码似乎可以正常工作:程序崩溃于

isalpha(n)

因为你声明

char n[2]

参数有一个char*类型的指针。但是islower只接受一个int参数,所以写成

就可以了
isalpha(n[0])

islower 相同。