尝试在程序中输入少于5个参数时,我一直遇到“分段错误”。我知道Java,但是对C还是陌生的,只是不确定发生了什么。我只是尝试将用户输入的kg(作为参数)转换为Prius的重量(十进制)。

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


int main(int argc, char *argv[]) //Argc is the argument count, argv is the argument vector
{

    //Initialize the toyota/user variables
    int toyota = 1325; //Toyota weight in kg
    int paramOne = atoi(argv[1]);
    int paramTwo = atoi(argv[2]);
    int paramThree = atoi(argv[3]);
    int paramFour = atoi(argv[4]);

    //This if will check to see if there are too many parameters
    if (argc >= 5)
    {
        printf("Error: Too many parameters.\n");
        printf("Usage: ./HW1 arg1 [arg2 ... arg4].\n");
    }

    //This if will check to see if there are too few parameters
    if (argc < 2)
    {
        printf("Error: Too few parameters.\n");
        printf("Usage: ./HW1 arg1 [arg2 ... arg4.\n");
    }


    //If there are a correct amount of parameters, this will print the TP count
    if ((argc >= 1) && (argc <= 4))
    {
        printf("%d number of parameters.\n", argc);

        if(argc >= 1)
        {

            printf("%d kg = %d TP.\n", paramOne, paramOne/toyota); //Parameter divided by TP
        }

        if(argc >= 2)
        {
            printf("%d kg = %d TP.\n", paramTwo, paramTwo/toyota);
        }

        if(argc >= 3)
        {
            printf("%d kg = %d TP.\n", paramThree, paramThree/toyota);
        }

        if(argc >= 4)
        {
            printf("%d kg = %d TP.\n", paramFour, paramFour/toyota);
        }




    }

}

最佳答案

int paramOne = atoi(argv[1]);
int paramTwo = atoi(argv[2]);
int paramThree = atoi(argv[3]);
int paramFour = atoi(argv[4]);

如果是argc <= 4,则这些调用会调用 undefined 的行为。请先测试argc,如果参数不足,请不要调用atoi

10-08 14:35