gpt4 book ai didi

c - 使用 argv[] 时出现段错误

转载 作者:行者123 更新时间:2023-12-02 07:28:00 27 4
gpt4 key购买 nike

我在尝试向程序中输入少于 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这些调用调用未定义的行为。测试argc之前不要打电话atoi如果没有足够的参数。

关于c - 使用 argv[] 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com