首页 > 解决方案 > 我在 C 中的 decToBase 方法出错并返回

问题描述

我正在研究 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”作为结果。

标签: cchardecimalbitbase

解决方案


在您的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);
}

这仍然不是超级理想,因为您的decToBase()函数不知道有多大outbuf,并且可能发生溢出,因此经验和/或偏执的程序员也会传递 outbuf 的大小,因此您的函数知道要使用多少。

但这是您稍后会进行的步骤。


推荐阅读