简体   繁体   English

具有0个命令行参数的简单程序分段错误

[英]Simple program Segmentation Faults with 0 command line parameters

so I have the following program which outputs the parameter with the maximum length. 所以我有以下程序输出最大长度的参数。 I want to make an exception so when I give it 0 parameters I get an error telling me that I need at lest one parameter. 我想做一个例外,因此当我给它提供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

This is my code but for some reason I am getting a segmentation error when I'm giving it 0 arguments, instead of the message. 这是我的代码,但是由于某些原因,当我给它0个参数而不是消息时出现分段错误。

Any thoughts? 有什么想法吗?

Edit after editing the question: Also you're using argv[1] before you checked argc . 编辑问题后进行编辑:同样,在检查argc 之前,您还使用了argv[1] This is an error. 这是一个错误。

If you pass no arguments, argc is going to be 1 (because argv[0] is usually the executable name). 如果不传递任何参数,则argc将为1 (因为argv[0]通常是可执行文件名称)。

So 所以

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
    if(argc<=1)
    {
        printf("You cannot have 0 parameters\n");
        exit(255);
    } else
    {
        int i;
        int maxLength = 0;
        const char* maxString = 0;

        for(i = 1; i < argc; ++i)
        {
            // find out the length of the current argument
            int length = strlen(argv[i]);
            if(maxLength <= length)
            {
                maxLength = length;
                maxString = argv[i];
            }
        }
        printf("Largest string is %s\n", maxString);
    }
} // main

如果在命令行中给零参数,则argc将为1而不是0。可执行文件的名称将为第一个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM