[英]Is char variable always represented as dereferenced char*[2] with {'x',\0}?
I tried this method to convert a char digit to an integer digit ('3'->3) and it seems to work. 我试过这种方法将一个char位数转换为一个整数('3'-> 3),它似乎起作用。
char c='x';
int i=atoi(&c);
My question is, will this always work? 我的问题是,这将始终有效吗?
Is there always a NULL character after the first character? 在第一个字符之后是否总是有NULL字符?
There is another way to do this using implicit typecast, but I am not sure it is a good practice. 还有另一种使用隐式类型转换的方法,但是我不确定这是一个好习惯。 Actually, I am pretty surprised there are no warnings even using -Wall and -Wextra.
实际上,我非常惊讶,即使使用-Wall和-Wextra也没有警告。
int i = c - '0';
Note I am using GCC 4.8.2 and MinGW. 注意我正在使用GCC 4.8.2和MinGW。
This compiles but it's undefined behavior. 这可以编译,但是它是未定义的行为。
A char
is just a character. char
只是一个字符。 No null byte following. 之后没有空字节。
std::atoi
expects a null byte, though, so invoking std::atoi(&c)
compiles but yields undefined behavior. std::atoi
期望为空字节,因此调用std::atoi(&c)
编译,但会产生未定义的行为。 This line, 这条线
int i = std::atoi("x");
is well-defined, though, because the string "x"
is a char[2]
and null-terminated. 但是,由于字符串
"x"
是char[2]
且以null终止,因此定义明确。
int i = c - '0';
is alright because 1 the C++11 standard and the C99 standard 2 guarantee the order of character digits. 没问题,因为1 C ++ 11标准和C99标准 2保证了字符数字的顺序。
1 as @ShafikYaghmour noted in the comments to your question 1就像@ShafikYaghmour在对您的问题的评论中指出的那样
2 Thanks to @ShafikYaghmour again! 2再次感谢@ShafikYaghmour!
atoi
expects null terminated C-string. atoi
期望null终止的C字符串。
since you didn't provide it (you provided a pointer to character) this is undefined behaviour. 由于未提供(您提供了指向字符的指针),因此这是未定义的行为。
for the second line of code - this generally works if you can guarantee that the character is indeed a digit. 对于第二行代码-如果可以保证字符确实是数字,通常可以使用。 for example , the character
#
will yield a result but may not the result you'd expect. 例如,字符
#
将产生结果,但可能不会产生您期望的结果。
some solution is to use std::stoi
: 一些解决方案是使用
std::stoi
:
try{ int x = std::stoi(std::string() + c) } catch(...) {/*handle*/}
This will work as long as next to the memory space where c is allocated is a \\0. 只要在分配c的内存空间旁边为\\ 0,它就可以工作。 In other words, it's just luck.
换句话说,这只是运气。 You should use
int i = c - '0'
您应该使用
int i = c - '0'
But be aware that every character will be mapped to int (fe int i = 'a' - '0'
) 但是请注意,每个字符都将映射到int(fe
int i = 'a' - '0'
)
To avoid this you could do something like: 为了避免这种情况,您可以执行以下操作:
int i = c=>'0' && c<='9' ? c-'0' : -1; //-1 represents not valid values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.