【发布时间】:2021-05-21 10:53:26
【问题描述】:
所以我参加了哈佛 cs50 在线课程(2021x 版)的第 2 周。我们应该编写一个加密文本的程序,将每个字母的 ASCII 码移动一定的量,由用户通过命令行决定。 Here is the full problem. 我快完成了,但是当我尝试运行程序时(它编译得很好),它告诉我有一个分段错误。我真的不明白这个问题。我读过这个问题与访问无法访问的某个内存部分有关?我该如何解决这个问题?先感谢您! 这是我的代码..
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int main(int argc, string argv[])
{
int k, i;
if (argc == 2 && isdigit(argv[1]) && argv[1] > 0)
{
k = (int) argv[1];
string plaintext = get_string("plaintext: ");
printf("cyphertext: ");
for (i = 0; i < strlen(plaintext); i++)
{
if (islower(plaintext[i]) || isupper(plaintext[i]))
{
printf("%c", (((plaintext[i] + k) - 97) % 26) + 97);
return 0;
}
}
}
else
{
printf("Usage: ./caesar key");
return 1;
}
}
【问题讨论】:
-
Debugging is a useful skill, now would be a great time to try it. 至少调试器会提示您崩溃发生的位置。
-
你能显示
string类型的声明吗?argv[1]是指向字符串的指针,(int) argv[1]不能得到argv[1]的十进制值,而是字符串的地址。对不起我的英语不好。 -
其他异常可见:
argv[1]>0不是一个定义明确的操作(再次指针),return 0在处理完第一个字母后看起来也有点不合适。 -
@guapi 好像是
typedef char *string;,见github.com/cs50/libcs50/blob/develop/src/cs50.h -
isdigit(argv[1])应该是isdigit(*argv[1])(或isdigit(argv[1][0])。k = (int) argv[1];应该是k = atoi(argv[1]);或使用strtol的类似名称。
标签: c segmentation-fault cs50 caesar-cipher