【问题标题】:Function produces null string instead of output (C)函数产生空字符串而不是输出 (C)
【发布时间】:2014-12-14 16:10:38
【问题描述】:

我正在编写一个程序,可以将基数为 10 的数字转换为 2 到 16 之间的不同基数。我已经编写了这样的函数,我认为它是正确的:

char* baseConversion(int number, int base, char *word)
{
       
       if (number != 0) {
  
       int x = number % base;
       
       if( x > 9){
           
           if(x == 10)
           *word = 'A';
           
           if(x == 11)
           *word = 'B';
           
           if(x == 12)
           *word = 'C';
           
           if(x == 13)
           *word = 'D';
           
           if(x == 14)
           *word = 'E';
           
           if(x == 15)
           *word = 'F';
           
           baseConversion(number/base, base, word+1);
           
           }
           
       else {
            *word = x;
            baseConversion(number/base, base, word+1);
            }
        
        
       
       
       }
       
}

我设置了我的主要功能来测试它:

int main(){
        int num, base;
        
        char word[20];
        
        scanf("%d %d", &num, &base);
        
        baseConversion(num, base, word);

        printf("%s", word);
        
        system("PAUSE");
        
        
        
        }

当我输入它时(我的测试用例是 15 16,应该评估为 F),我得到的是 null 这个词。我没有正确传递我的字符串?还是我的指针算术关闭了?

注意:我也知道这会给我一个相反的答案,当我没有得到空答案时,我可以使用修复它。

【问题讨论】:

  • 你的函数中没有'return'语句应该按照函数定义返回
  • @KevalDoshi:没关系,因为 OP 无论如何都会忽略返回的内容 :)
  • 但是指针不应该允许它在 return 语句之外被修改吗?
  • 不是问题:你声明函数返回一个字符串,你没有,但你对它的调用并没有使用它。
  • *(word+1)='\0';放在baseConversion(..)的末尾

标签: c string pointers null


【解决方案1】:

对于num<10,您没有为该数字插入字符(例如,您应该在x==0 时输入'0')。验证:尝试一个所有以 16 为基数的字母的值。(当然,你也永远不会终止字符串,所以你可能会看到一些时髦的东西......)

(此外,您的代码不适用于 16 以外的基数,因为您在其中硬编码了 16 个。)

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2019-11-10
    • 2020-01-10
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多