正确的函数输出导致printf中的垃圾

时间:2013-06-24 14:40:10

标签: c function printf

我正在练习c编程,我被要求编写一个整数到字符串的函数。我的代码如下。

在我尝试在main函数中打印出函数return之前,一切都是正确的。正如“自动”在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;

}

2 个答案:

答案 0 :(得分:1)

如果没有完整的itob函数,至少是str的定义,很难回答,因为它可能引用堆栈上的变量而不是堆,所以当函数{ {1}}返回,对该内存的引用将丢失。

答案 1 :(得分:0)

在尝试保留编码风格的同时,下面是一个候选解决方案。您需要在s中撤消stritob的角色。 'str'是你的工作缓冲区,'s'是传入和返回的目标。同时将i初始化为99,而不是100以保持在str

#include <stdio.h>
#include <stdio.h>

char* itob(int n, char s[100], int b);
char reverse(char s[100], char i);

int main(void) {
  int n;
  int b;
  //  int c = 0;
  char* str;
  char s[100];
  //    ...
  b = 8;
  n = 1234;
  str = itob(n, s, b);
  printf("%s\n", str);   //wrong
  b = 16;
  str = itob(n, s, b);
  printf("%s\n", str);   //wrong
  // main();
}


char* itob(int n, char s[100], int b)
{
int i=100-1,c/*,firstdig*/,a;
char str[100];
if(b==8)
    printf("0");
else if(b==16)
    printf("0x");

do
{
    c=n%b;
    if(c>9)
            str[i--]=c-10+'A';
        else
            str[i--]=c+'0';
} while((n/=b)>0);
a=0;
c=i+1;
while(c!=(101-1))
    {
        s[a]=str[c];
        a++;
        c++;
    }
s[a]='\0';
return s;
}