Search code examples
cstringpointersrecursiondynamic-memory-allocation

Read in a line using recursion and return a pointer to the string


I need to create a char *read_line(void) function which reads in a character recursively so with each recursive call it creates a local char variable and when enter character has been read in, it can determine how much memory is needed to be allocated so it can eventually return a pointer to a string. The string must end with \0 terminator. I may only use one malloc call, I cannot use any global or static variables or any other containers. I may use any custom helper functions. Prohibited words: realloc;calloc;strcpy;strncpy;10 I know this is impractical, but it's a homework assignment.


Solution

  • The final call will need to do

    char *str = malloc(i+1);
    str[i] = 0;
    return str;
    

    Other calls will need to do

    char *str = read_line_helper(...);
    str[i] = ch;
    return str;
    

    That means that each call needs an i that's one more than its caller. This can easily be achieved by passing i+1 to the recursive function.

    char *read_line_helper(size_t i) {
       char ch = ...;
    
       char *str;
       if (...) {
          str = malloc(i+1);
          str[i] = 0;
       } else {
          str = read_line_helper(i+1);
          str[i] = ch;
       }
    
       return str;
    }
    

    The first call takes 0.

    char *read_line(void) {
       return read_line_helper(0);
    }