Command line integer changing value?

Viewed 57

I'm trying to parse two arguments from the command line right now: a string, and an int. I'm trying to do this parsing without the use of built in parsers like getopt or argp. I've figured out how to parse the string correctly, but when I parse the int, it changes the value? I'm not sure why this happens. Here is my code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    char* filename;
    int prefix;
    int x;
    for(x = 0; x < argc; x++)
    {
        if(x == 1)
        {
            filename = argv[x];
        }
        if(x == 2)
        {
            prefix = *argv[x];

        }
    }
    printf("%s\n", filename);
    printf("%d\n", prefix);
}

When I pass in the arguments: filename 70

It will print out: filename 55

Why is it changing my int value like this? I've tested it with a variety of values, and I noticed it's not even a consistent offset value. How can I fix this to parse my int correctly? Thanks.

1 Answers

Your parameter (70) is a string. When you do:

prefix = *argv[x];

you are converting a character (7) to an integer. This will give you the ASCII value of 7 which is 55. Make the following change. This will convert the string to an integer.

prefix = atoi(argv[x]);

atoi is ASCII to Integer

Related