c - 我的 C 中的 decToBase 方法出现错误并返回

标签 c char decimal bit radix

我正在使用 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/

相关文章:

c++ - 如何将表示二进制的 int vector 转换为表示十进制数的 int vector ? C++

C# 十进制到十六进制 & 十六进制到十进制/十六进制到 ascii 在 LINQ

java - 如果需要,将 Double 格式精确到小数点后 2 位

c - 服务器无法读取给定 HTTP POST 的负载

c++ - 将列表元素分配给 char*

integer - 检查 Prolog 中的字符是否为数字?如何实现整数/1?

java - 无法转换为 char 吗? : operator

c++ - 为什么在 C 和 C++ 中算术运算之前必须将 Short 转换为 int?

使用 C 从另外两个数组中的最小整数创建第三个数组

C Lib 设计 - 结构和内存管理 [最佳实践]