そのため、最大長のパラメーターを出力する次のプログラムがあります。例外を作成したいので、0 個のパラメーターを指定すると、少なくとも 1 つのパラメーターが必要であるというエラーが表示されます。
// 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 に指定すると、セグメンテーション エラーが発生します。
何かご意見は?