2

I keep getting these strange negative values when I run the code. Does anyone know what they are and how to get just an int (For example 10, 20, 8...)? Why do I always get a different and wrong value? When I run the code with arguments 2 and 3 it should output 10...

int main(int argc, char *argv[]) {
  int h;
  int a;
  int b;
  a = (int) argv[1];
  b = (int) argv[2];
  if (argc == 3) {
    h = 2 * (a + b);
    printf("The perimeter of the rectangle is %d\n", h);
  } else {
    fprintf(stderr, "Usage: %s <arguments>\n", argv[0]);
  }
}

Output:
The perimeter of the rectangle is -1874251136
or
The perimeter of the rectangle is -1424723328
or
The perimeter of the rectangle is -940059169
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
makfazlic
  • 33
  • 4
  • 2
    Er... you're casting `char *` variables to `int`? Why? What in the world is that supposed to accomplish? You need to be using `strtol()` or something along those lines if you want to convert a string holding a number to an int. – Shawn Feb 07 '19 at 11:25

3 Answers3

3

Test too late

if(argc==3){ tests for required argc, but unfortunately after using argv[1], argv[2]. Move test before and exit if not as needed. Note: good use of error message to stderr.

if (argc != 3) {
  fprintf(stderr,"Usage: %s <arguments>\n", argv[0]);
  return -1; // or return EXIT_FAILURE
}  

Incorrect conversion

Code is converting the pointer and not the referenced text.

#include <stdlib.h>

// a = (int)argv[1];
a = atoi(argv[1]);

Robust code would use strtol() or perhaps roll your own `strtoi()'

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
2

argv is an array of pointers to char. I.e. it's an array of strings. The string "1" is not equal to the integer 1 (or even the character '1'). The fact that you're doing a cast should almost always be a red flag.

To convert a string to a number use the strtol function.

And always remember to check argc before accessing argv.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1
b = (int)argv[2]

The (int) is a cast of the pointer value -- it just converts the type

Instead try use atoi or strtol to convert a string to an integer value.

Soren
  • 14,402
  • 4
  • 41
  • 67