谁能告诉我为什么我会出现分段错误(cs50 替换)
Can anyone tell me why im getting a Segmentation Fault (cs50 substitution)
在我的程序中,我得到了我控制的错误,但是当我试图避免那些预设错误并输入我希望用户输入的内容时,它 returns 一个分段错误。
#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 导致了分割。这里稍微优化一下代码。
#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");
}
在我的程序中,我得到了我控制的错误,但是当我试图避免那些预设错误并输入我希望用户输入的内容时,它 returns 一个分段错误。
#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 导致了分割。这里稍微优化一下代码。
#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");
}