我正在使用 C 语言开发一种方法,尝试将小数转换为其基数。我在返回 Char* 时遇到问题。我仍然不确定如何返回指针。当我编译这段代码时,我收到一条警告:
“警告:函数返回局部变量的地址 [-Wreturn-local-addr]”。 这和我的res性格有关。我不确定为什么我不能返回 res,如果它是一个字符。如果我无法返回 res,我不明白我应该返回什么。请帮忙。
//return res;
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else if(num = 10)
{
return (char)(num - 10 + 'A');
}
else if(num = 11)
{
return (char)(num - 11 + 'B');
}
else if(num = 12)
{
return (char)(num - 12 + 'C');
}
else if(num = 13)
{
return (char)(num - 13 + 'D');
}
else if(num = 14)
{
return (char)(num - 14 + 'E');
}
else if(num = 15)
{
return (char)(num - 15 + 'F');
}
}
// Utility function to reverse a string
void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
{
char temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
char* decToBase(int base, int dec)
{
int index = 0; // Initialize index of result
char res[100]; // Convert input number is given base by repeatedly
// dividing it by base and taking remainder
while (dec > 0)
{
res[index++] = reVal(dec % base);
dec /= base;
}
res[index] = '\0';
// Reverse the result
strev(res);
return res;
int main()
{
char* base = decToBase(16, 248);
}
无论如何,我想要的结果是让方法返回“f8”作为结果。
最佳答案
在您的decToBase()
函数中,它警告的问题是使用char res[500];
,它是一个在堆栈上分配为的数组局部变量。当函数返回时,这些都会被丢弃,因此如果您返回一个指向 res 数组(或地址)的指针,则该指针指向堆栈上的垃圾。
您必须找到其他方法来管理此分配,尽管有些人可能建议使用 malloc()
从系统分配内存,但这可能是一个坏主意,因为它会导致以下问题:内存泄漏。
更好的方法是传入您想要填充的缓冲区,然后使用它。然后调用者进行分配,您不必担心内存泄漏。
char *decToBase(int base, int dec, char *outbuf)
{
int index = 0; // Initialize index of result
// Convert input number is given base by repeatedly
// dividing it by base and taking remainder
while (dec > 0)
{
outbuf[index++] = reVal(dec % base);
dec /= base;
}
outbuf[index] = '\0';
// Reverse the result
strev(outbuf);
return outbuf;
}
然后你的 main
函数将如下所示:
int main()
{
char decbuf[500];
decToBase(16, 248, decbuf);
printf("Buffer is %s\n", decbuf);
}
这仍然不是 super 理想,因为你的 decToBase()
函数不知道 outbuf
有多大,并且溢出是可能的,所以经验和/或偏执的程序员还会传入 outbuf 的大小,以便您的函数知道要使用多少。
但这是您稍后会执行的步骤。
关于c - 我的 C 中的 decToBase 方法出现错误并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617154/