Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char isn't converting to int

Tags:

c

argv

For some reason my C program is refusing to convert elements of argv into ints, and I can't figure out why.

int main(int argc, char *argv[])
{

    fprintf(stdout, "%s\n", argv[1]);

    //Make conversions to int
    int bufferquesize = (int)argv[1] - '0';

    fprintf(stdout, "%d\n", bufferquesize);
}

And this is the output when running ./test 50:

50

-1076276207

I have tried removing the (int), throwing both a * and an & between (int) and argv[1] - the former gave me a 5 but not 50, but the latter gave me an output similar to the one above. Removing the - '0' operation doesn't help much. I also tried making a char first = argv[1] and using first for the conversion instead, and this weirdly enough gave me a 17 regardless of input.

I'm extremely confused. What is going on?

like image 318
limasxgoesto0 Avatar asked Mar 19 '12 20:03

limasxgoesto0


2 Answers

Try using atoi(argv[1]) ("ascii to int").

like image 143
Scott Hunter Avatar answered Sep 20 '22 15:09

Scott Hunter


argv[1] is a char * not a char you can't convert a char * to an int. If you want to change the first character in argv[1] to an int you can do.

int i = (int)(argv[1][0] - '0');

I just wrote this

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

int main(int argc, char **argv) {
    printf("%s\n", argv[1]);

    int i = (int)(argv[1][0] - '0');

    printf("%d\n", i);
    return 0;
}

and ran it like this

./testargv 1243

and got

1243
1
like image 35
twain249 Avatar answered Sep 19 '22 15:09

twain249