簡體   English   中英

具有0個命令行參數的簡單程序分段錯誤

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

所以我有以下程序輸出最大長度的參數。 我想做一個例外,因此當我給它提供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個參數而不是消息時出現分段錯誤。

有什么想法嗎?

編輯問題后進行編輯:同樣,在檢查argc 之前,您還使用了argv[1] 這是一個錯誤。

如果不傳遞任何參數,則argc將為1 (因為argv[0]通常是可執行文件名稱)。

所以

#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