【发布时间】:2017-08-05 00:27:21
【问题描述】:
我正在尝试编写一个对用户提供的字符串进行 Caesar 加密的程序,但每次我尝试运行它时都会弹出错误“Segmentation Fault”。我做错了什么?
int main(int argc, string argv[])
{
if (argc != 2)
{
return 1;
}
int key = atoi(argv[1]);
printf("Plaintext: ");
string Ptext = get_string();
string cipher = 0;
if(Ptext != NULL)
{
for(int i = 0, n = strlen(Ptext); i < n; i++)
{
if(isalpha(i))
{
if(isupper(i))
{
cipher += toupper(((i + key) % 26));
}
else
{
cipher += tolower(((i + key) % 26));
}
}
cipher += i;
}
printf("Ciphertext: %s", cipher);
printf("\n");
}
}
【问题讨论】:
-
你的代码在我看来像 C++。
string在 C 中不存在,字符串附加也不存在。什么是get_string()? -
这也是您在 if 语句中测试 if
i,索引值,而不是索引i处的字符的情况,例如Ptext[i] -
@FelixGuo 这个
cs50课程确实提供了typedef char *string... -
@AshleyMoe :我添加了标签cs50 和caesar-encryption,因为
string和get_string()的使用是常规的,除了在CS50 课程中。另请注意CS50 站点。 -
如果是 C,这个程序只是一个巨大的未定义行为。您只需对指针进行一些算术运算,然后取消引用它,这样 SegFault 就不足为奇了——我什至会说这是预期的行为
标签: c segmentation-fault cs50 caesar-cipher