argc with segmentation fault

the issue i am having is when i try and run the program, argv is giving me a segmentation fault when i only put in one command line argument. its temperature conversion program.
temp = atoi(argv[1]);
temp_type = *argv[2];
trying to have last if statement print if only a temperature is entered.
example with only entering temperature: ./a.out 72

cout << fixed << setprecision(1);

// displays converted temps of Fahrenheit to celcius and kelvin
if (temp_type == 'F') {
cout << temp << "F is " << F_C << "C and " << F_K << "K" << endl;
}

// displays converted temps of Celcius to fahrenheit to kelvin
if (temp_type == 'C') {
cout << temp << "C is " << C_F << "F and " << C_K << "K" << endl;
}

// displays converted temps of Kelvin to fahrenheit and celsius
if (temp_type == 'K') {
cout << temp << "K is " << K_F << "F and " << K_C << "C" << endl;
}

// displays fault if wrong temperature type is entered
if ((temp_type != 'F') && (temp_type != 'C') && (temp_type != 'K')) {
cout << temp_type << " is not valid temperature type." << endl;
}

// displays fault if only temperature is entered
if (argv) {
cout << "You must enter two arguments." << endl;
}

cout << "$" << endl;
Last edited on
Well to start using argc won't cause a segmentation fault. However trying to access argv[] out of bounds will usually cause a segmentation fault. In your example you are attempting to access the argv[] array out of bounds. When you have one argument the valid indexes of argv[] would be either 0 or 1. Also using the assignment operator with C-strings is not a good idea.
segmentation fault when i only put in one command line argument


Well that's your problem. You just need to add an if statement to make sure the user entered 2 numbers on the command line. You almost have that at the end there, but what you really want is if(argc != 3) at the top of the program, before you dereference argv in any way. Remember that it must be 3, not 2, because argv[0] is the name of the program.
If you pass one command line argument,then argc will be 2, and the argument that you passed will be found at argv[1].
Topic archived. No new replies allowed.