我想在使用命令行参数和isalpha()时澄清我对分段错误的理解,但这种特殊情况让我更困惑。因此,我按照this的建议,将argv[1]声明为char *作为一种绕过它的方法,所以请回答。
但是,如果我使用的命令行参数少于2个,则仍然会发生Segmentation Fault,并且在If3条件中忽略isalpha()
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> //atoi is here
int main(int argc, char* argv[]){
char *input = argv[1];
// Error handling
if ((argc > 2) || (argc < 1) || (isalpha(input[1])))
{
printf("Unwanted input\n");
return 1;
}
return 0;
}为什么不使用命令行参数时会得到undefined behaviour,为什么isalpha()会被忽略,而不是给我一个seg错误?
感谢您抽出时间阅读这篇文章
发布于 2021-01-01 03:57:38
在不带参数的情况下执行程序时,argc为1 (因为程序名本身也算作arg),而argv[1]为NULL。
(argc > 2) || (argc < 1) // Considers argc == 1 and argc == 2 acceptable应该是
(argc > 2) || (argc < 2) // Only considers argc == 2 acceptable或者只是
argc != 2https://stackoverflow.com/questions/65524966
复制相似问题