所以我有以下程序输出最大长度的参数。我想做一个例外,所以当我给它 0 个参数时,我得到一个错误,告诉我我至少需要一个参数。
// Program which given an number of program parameters
// (command-line parameters, calulates the length of each one
// and writes the longest to standard output.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int i;
int maxLength = strlen(argv[1]);
char* maxString = argv[1];
if (argc<=0)
{
printf("You cannot have 0 parameters\n");
exit(0);
}
for(i = 2; i < argc; ++i)
{
// find out the length of the current argument
int length = strlen(argv[i]);
if (maxLength < length)
{
maxLength = length;
maxString = argv[i];
} // if
} // for
printf("Largest string is %s\n", maxString);
} // main
这是我的代码,但由于某种原因,当我给它 0 个参数而不是消息时,我得到了一个分段错误。
有什么想法吗?