函数产生空字符串而不是输出(C)

时间:2014-10-19 16:35:17

标签: c string pointers null

我正在编写一个程序,可以将基数为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。我没有正确传递我的字符串?或者是我的指针算术了吗?

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

1 个答案:

答案 0 :(得分:0)

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

(另外,你的代码不适用于16以外的基数,因为那里有16个硬编码。)