Char isn't converting to int

天涯浪子 提交于 2019-12-03 12:13:17

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

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

You are just trying to convert a char* to int, which of course doesn't make much sense. You probably need to do it like:

int bufferquesize = 0;
for (int i = 0; argv[1][i] != '\0'; ++i) {
   bufferquesize *= 10; bufferquesize += argv[1][i] - '0';
}

This assumes, however, that your char* ends with '\0', which it should, but probably doesn't have to do.

(type) exists to cast types - to change the way a program looks a piece of memory. Specifically, it reads the byte encoding of the character '5' and transfers it to memory. A char* is an array of chars, and chars are one byte unsigned integers. argv[1] points to the first character. Check here for a quick explanation of pointers in C. So your "string" is represented in memory as:

['5']['0']

when you cast

int i = (int) *argv[1]

you're only casting the first element to an int, thus why you

The function you're looking for is either atoi() as mentioned by Scott Hunter, or strtol(), which I prefer because of its error detecting behaviour.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!