時出現分段錯誤我試圖在程序中輸入少於5個參數時,仍然遇到「分段錯誤」。我認識Java,但對C來說是新手,我只是不確定發生了什麼。我只是簡單地嘗試將用戶輸入的kg(作爲參數)轉換爲Prius的重量數,即小數。使用argv []
#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);
}
}
}
我應該這樣做的計劃?爲什麼需要一些很多參數? – 2014-09-02 22:36:45
如果輸入的參數少於5個,爲什麼你不希望出現段錯誤? 'argv [4]'會超出界限,其他的也可能會超出界限。 – 2014-09-02 22:37:03
延遲調用atoi,直到您測試了argc。 – 2014-09-02 22:38:20