【问题标题】:CS50 / BEGINNER - Segmentation fault in nested for loop in CCS50 / BEGINNER - C 中嵌套 for 循环中的分段错误
【发布时间】:2020-10-30 13:46:24
【问题描述】:

我正在尝试编写代码,该代码将从明文字符串输入中获取每个数字,如果是字母,则输出不同的字母,由替换键(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:  ");

非字母应按原样打印。

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

然而,这个循环在我运行它时会返回一个段错误,但在调试时不会:

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

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

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

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

【问题讨论】:

  • 有一个内置函数strchr() 会在字符串中搜索匹配的字符,您不需要编写自己的循环。
  • 为什么要为 1 个字符的字符串创建数组?只需使用char 变量即可。
  • isalpha(n) 错误,应该引起编译器警告。 isalpha() 的参数应该是 n[0],而不是 n
  • 提示:节省时间,启用所有警告。
  • @Barmar strchr(),据我所知,将返回一个指针,我仍然不知道如何使用指针(或者它们究竟是什么)。

标签: arrays c for-loop segmentation-fault cs50


【解决方案1】:

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

isalpha(n)

因为你声明了

char n[2]

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

isalpha(n[0])

islower 也一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-04
    • 2016-12-08
    • 1970-01-01
    • 2021-07-31
    • 2013-08-21
    • 2017-09-13
    • 1970-01-01
    • 2016-02-07
    相关资源
    最近更新 更多