gpt4 book ai didi

c - Strtol 返回错误的值

转载 作者:行者123 更新时间:2023-11-30 19:07:05 25 4
gpt4 key购买 nike

这周我刚刚开始学习c。

我正在尝试将单个字符转换为 long/int。
我的问题是,当我通过 main 调用 convenrtCharToInt 时,它返回正确的值,但是当我通过另一个函数调用此函数,并给它一个位于字符数组内的字符时,我得到 10 而不是 1。我曾经尝试只在函数中输入*“1”,但它仍然给我错误的值,它给我 10 而不是 1 作为长。

double base2ToBase10(char test[],int curBase){

double totalSum;
long currentNumber;
int arrayLength=countArray(test);
for(int i=0; i<arrayLength ;i++) {
currentNumber=convenrtCharToInt(test[i]);
if ((test[i] < *"1")) {
totalSum += 0;
} else {
totalSum += currentNumber*pow(curBase, arrayLength - 1 - i);

}

}return totalSum;}

long convenrtCharToInt(char c)
{
long postConvertValue = strtol ( &c,NULL, 10 );
return postConvertValue;

所以,如果我通过 main 调用它,无论我怎么做,它都会起作用,但如果我在调用 base2ToBase10 时尝试使用它,它就不会。

最佳答案

问题在于 &c 位于

long convenrtCharToInt(char c) {
long postConvertValue = strtol ( &c,NULL, 10 );

将指向单个字符的指针传递给需要以 \0 结尾的字符序列意义上的字符串的函数。因此,除非 c 的值为 0,函数 strtol 将访问 `c 范围之外的内存,从而产生未定义的行为。

要克服这个问题,你可以简单地写

int v = c - '0'; // substract ASCII-Code of digit '0' (i.e. 48)
return (v >= 0 && v <= 9) ? v : -1;

关于c - Strtol 返回错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47187773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com