I did this something like this:
/* convert the argv[1] into Integer and store the result in key
* using library function: strtol() to do it */
char **flag = NULL;
key = strtol(argv[1], flag, 10);
// if argv[1] is not all digits
if (**flag != '')
{
printf("Usage: ./caesar key
");
return 1;
}
But it throws a segmentation fault. I am not sure why.
In the C documentation, strtol
is prototyped as long int strtol(const char *nptr, char **endptr, int base)
. Why am I getting a segmentation fault?
And when change some parts of the code to char *flag
, strtol(argv[1], &flag, 10)
, and if (*flag != '')
, everything works as expected.
I understand (sort of) how making the edits corrects the code. However, I do not know why the original code does not work. Does anyone have a clue?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…