c - 谁能告诉我为什么我得到一个分段错误(cs50替换)
问题描述
在我的程序中,我得到了我控制的错误,但是当我试图避免这些预设错误并输入我希望用户输入的内容时,它会返回一个分段错误。
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
string key = argv[1];
if (argc < 2 || argc > 2)
{
printf("Usage: ./substitution key\n");
exit(1);
}
if (argc == 2 && strlen(key) < 26)
{
printf("Key must contain 26 characters.\n");
exit(1);
}
if (strlen(key) > 26)
{
printf("Key must contain 26 characters.\n");
exit(1);
}
for (int i = 0; i < 26; i++)
{
if (isalpha(key) == 0)
{
printf("MAKE SURE YOUR KEY ONLY HAS LETTERS\n");
}
}
printf("test");
}
解决方案
@Retired Ninja 很到位。isalpha on key 导致了分段。这是代码的稍微优化的方式。
#include <stdio.h>
#include "cs50.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
exit(1);
}
string key = argv[1];
int keylen = strlen(key);
if (keylen != 26)
{
printf("Key must contain 26 characters.\n");
exit(1);
}
for (int i = 0; i < 26; i++)
{
unsigned char const c = key[i];
if (!isalpha(c))
printf("MAKE SURE YOUR KEY ONLY HAS LETTERS\n");
}
printf("test\n");
}
推荐阅读
- c - 自上而下的归并排序。合并方法抽象交换方法
- python - 是否可以提取 Plotly Dash 图形中的图例以显示在第二个图像/容器中?
- pandas - 在 GridSearch 和交叉验证中,我只得到 XGBClassifier 的 `accuracy_score` 而不是 `roc_auc`
- ios - 如何将 iPhone 样式的表格视图变成 iPad 样式的表格视图 (Swift)
- c++ - Python3 C++ 模块 - 异常 - GIL 未持有
- python - python问题中的鼠标滚轮单击绑定
- python - python中的map函数,当为x^3映射大数给我负值时
- bootstrap-4 - 调整屏幕大小时,我正在制作卡片内联块,卡片没有响应
- javascript - 矩阵蛇阵
- .htaccess - 资产相对于根目录,但 html 文件位于子文件夹中