[英]convert a number from the given base to decimal
This is my code but it is not working; 这是我的代码,但它不起作用;
char *toBase(int number, int base) {
char *result=malloc(80);
char *ans=malloc(80);
int i=0,j,c;
while(number != 0) {
result[i] = number % base;
number = number / base; ++i;
}
for(j=i-1;j>=0;j--) {
if(result[j]>=10 && result[j]<=24) {
printf("%c",(result[j]+55));
*ans++=(result[j]+55);
} else {
printf("%d",(result[j]));
*ans++=(result[j]);
}
}
return ans;
}
The problem is that you modify the ans
pointer in the loop, so when you return ans
it no longer points to the beginning of the string, instead it points to where you should terminate the string. 问题是您在循环中修改了ans
指针,因此当您返回ans
它不再指向字符串的开头,而是指向应该终止字符串的位置。
Use a temporary variable initialized to be the same as ans
and return the one you don't modify. 使用初始化为与ans
相同的临时变量并返回您ans
的临时变量。
It should also be noted that you have a memory leak, you allocate memory for result
but you never free
it anywhere. 还应该注意的是,你有一个内存泄漏,你为result
分配内存,但你永远不会free
它。
Your problem is in the conversion of the numbers into text 您的问题在于将数字转换为文本
Try to add the value of '0' and 'A' resectively, as 尝试将'0'和'A'的值设为临界值,如
if(result[j]>=10 && result[j]<=24) {
printf("%c",(result[j]+'A'));
*ans++=(result[j]+'A');
} else {
printf("%c",(result[j]+'0'));
*ans++=(result[j]+'0');
}
and make sure to null terminate the string before returning it, like 并确保在返回之前将null终止字符串,例如
*ans++ = 0;
and also -- the statement 而且 - 声明
return ans;
will return the end of the string rather than the start -- so you will have to fix that as well, and of cause fix your memory leaks.... 将返回字符串的结尾而不是开始 - 所以你必须修复它,并且因为修复你的内存泄漏....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.