简体   繁体   English

在C的递归函数中连接char

[英]Concatenating a char in a recursive function in C

Even though I have more experience with higher level languages, I am having a lot of troubles understanding how memory allocation and how strings really work in C . 尽管我对高级语言有更多的经验,但是在理解内存allocation以及stringsC实际工作方式方面还是有很多麻烦。

I am trying to implement a very simple base converter that works recursively. 我正在尝试实现一个非常简单的递归工作的基本转换器。 The only thing is that it should return a char* instead of an int 唯一的事情是它应该返回一个char*而不是一个int

Here is my code. 这是我的代码。 I already tested the recursive calls and it works if I use integers. 我已经测试了递归调用,如果我使用整数,它可以工作。 So, the problem is definitely with the string part. 因此,问题绝对是字符串部分。 It gives me an infinite loop. 它给了我无限循环。

char* baseConversion(int num, int baseIn, int baseOut){

    //convert num to base ten

    int quotient = num / baseOut;

    int remainder = num % baseOut;

    char rem = (char)(((int)'0') + remainder);

    char *result = malloc(strlen(output) + 1);

    strcpy(result, rem);

    if (quotient == 0)
        return result;
    else
        return strcat(result, baseConversion(quotient, baseIn, baseOut));
}

Many thanks 非常感谢

Change: 更改:

strcpy(result, rem);

to: 至:

result[0] = rem;
result[1] = 0;

This will create a single-character string containing the character in rem . 这将创建一个包含rem字符的单字符字符串。

You also may need to fix: 您可能还需要修复:

malloc(strlen(output)+1)

as there's no variable named output in your function. 因为您的函数中没有名为output的变量。

If I have understood correctly what you are saying about then what you need is the following 如果我已正确理解您在说什么,那么您需要的是以下内容

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * baseConversion( unsigned int x, unsigned int base )
{
    unsigned int digit;
    char *p = NULL;
    size_t n = 2;

    if ( base > 10 || base < 2 ) base = 10;

    digit = x % base;

    if ( x / base ) p = baseConversion( x / base, base );

    if ( p ) n += strlen( p );

    p = realloc( p, n );

    *( p + n  - 2 ) = digit + '0';
    *( p + n  - 1 ) = '\0';

    return p;
}   


int main(void) 
{
    unsigned int x = 255;

    char *p = baseConversion( x, 10 );

    printf( "%s\n", p );

    free( p );

    p = baseConversion( x, 8 );

    printf( "%s\n", p );

    free( p );

    p = baseConversion( x, 2 );

    printf( "%s\n", p );

    free( p );

    return 0;
}

The output is 输出是

255
377
11111111

PS It is funny when one answer is marked as the best but the code will be used from other answer.:) PS将一个答案标记为最佳答案是很有趣的,但是其他答案将使用该代码。:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM