0

Hi I'm new to C and I am trying to print an 8 when running the program with "factorial 8". Instead of getting an 8, I am getting 56. Can anyone explain why?

#include <stdio.h>

int main(int argc, char **argv)
{
    int input;

    if(argv[1] == NULL)
    {
        printf("Error: please supply an integer on the command line.\n");
        return 0;
    }

    input = *argv[1];
    printf("%d", input);

    return 0;
}
mpromonet
  • 8,785
  • 40
  • 48
  • 80
Tin La
  • 15
  • 7
  • 1
    argv[1] is a pointer to a character. You need to convert argv[1] to an integer using the function atoi when assigning it to i. If you'll notice that 56 is the ascii code for '8'. – bruceg Feb 02 '16 at 00:39

3 Answers3

2

You're getting a 58 because you're assigning the integer value of whatever argv[1] happens to pointing to. You may want to look into atoi()

 input = atoi(argv[1]);

I'd really recommend that you verify that you have arguments by checking the number of arguments in argc rather than just dereferencing argv[1] and checking if it's null.

David Hoelzer
  • 14,530
  • 4
  • 39
  • 61
1

Here :

input = *argv[1];

you are trying to assign string(argv[1]) to int.

You should go like:

input = atoi(argv[1]);
J.Kennsy
  • 454
  • 5
  • 17
0

The arguments in the main function are passed as strings. So when you do

input = *argv[1];

You are assigning string value to input. If you look at ascii table you can see the character "8" has the value of 56.

You can use atoi() function as other answer emphasize or, you can use strtol() to convert string into the integer.

For a more detailed answer about atoi() and strtol() check the answer https://stackoverflow.com/a/3421555/1589566

Community
  • 1
  • 1
berkuqo
  • 2,577
  • 4
  • 24
  • 41