【发布时间】:2022-12-11 19:55:25
【问题描述】:
我正在尝试解决哈佛 CS50 课程中的 Caesar pset,我认为我基本上是在正确的方法上,但我刚开始收到错误“分段错误(核心已转储)”。
我对编码仍然非常陌生,这就是为什么我在查看其他类似问题时在解决问题时遇到了一些麻烦。也许有人可以看一眼我的代码并提供帮助。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char rotate(char c, int n);
int main(int argc, string argv[])
{
// SAVE CLA AS VARIABLES
string plaintext = get_string("plaintext: ");
int key = atoi(argv[1]);
string cipher = "";
int length = strlen(plaintext);
for (int i = 0; i < length; i++)
{
cipher[i] = rotate(plaintext[i], key);
}
printf("%s\n", cipher);
}
char rotate(char c, int n)
{
//test if c = key is in right range
c = c + n;
while (c > 122)
{
c = c - 122 + 64;
}
return c;
}
【问题讨论】:
-
第一步应该始终是在调试器中运行您的程序。它将向您显示分段错误发生的位置。您可以检查变量并查找意外值。
标签: c segmentation-fault cs50 coredump