我正在自己练习 C 编程,有人要求我编写一个整数到字符串的函数。我的代码如下。
一切都是正确的,直到我尝试打印出主函数中的函数返回。正如“auto”在 Visual Studio 中向我展示的那样,我有正确的返回值,但它在 printf 函数中被搞乱了。有什么建议吗?谢谢。
#include <stdio.h>
char* itob(int n, char s[100], int b);
char reverse(char s[100],char i);
int main(void)
{
int n,b,c=0;
char* str;
char s[100];
...
str=itob(n,s,b);
printf("%s",str); //wrong
main();
}
char* itob(int n, char s[100], int b)
{
int i=100,c,firstdig,a;
char str[100];
if(b==8)
printf("0");
else if(b==16)
printf("0x");
do
{
c=n%b;
if(c>9)
s[i--]=c-10+'A';
else
s[i--]=c+'0';
} while((n/=b)>0);
a=0;
c=i+1;
while(c!=101)
{
str[a]=s[c];
a++;
c++;
}
str[a]='\0';
return str;
}
最佳答案
如果没有完整的 itob
函数,至少没有 str
的定义,就很难回答,因为它可能引用堆栈上的变量,而不是堆上的变量,因此当函数 itob()
返回时,对该内存的引用就会丢失。
关于正确的函数输出导致 printf 中产生垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278218/