我的decToBase方法在C语言中的错误,带有返回

问题描述 投票:0回答:1

我正在C中的一种方法中尝试将十进制转换为其基数。我在返回Char *时遇到麻烦。我仍然不确定如何返回指针。当我编译这段代码时,我得到一个警告,说

“警告:函数返回局部变量[-Wreturn-local-addr]的地址”。这与我的res角色有关。我不确定为什么不能返回res(如果是char)。我不明白如果我不能退回资源,我应该退还什么。请帮忙。

 //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”作为结果。

c char decimal bit base
1个回答
0
投票

decToBase()函数中,警告的问题是使用char res[500];,它是在堆栈上作为局部变量分配的数组。当函数返回时,这些都将被丢弃,因此,如果您返回指向res数组的指针(或地址),则该指针指向堆栈上的垃圾。

[您必须找到其他方法来管理此分配,尽管有些人可能建议使用malloc()从系统分配内存,但这可能不是一个好主意,因为它正在询问内存泄漏问题。

最好是传递您要填充的缓冲区,然后使用它。然后caller进行分配,您不必担心内存泄漏。

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的大小,因此您的函数知道要用多少。

但这是您稍后要执行的步骤。

© www.soinside.com 2019 - 2024. All rights reserved.