Writing code for indentation code

My goal is to write a C program that discards the C code specified in char *input

. The style of one level of indentation is specified on the line const char *pad

. I wrote the following code which works in my head but not in practice. There must be an error somewhere, but I can't find it. Also, I can't figure out why Valgrind doesn't like the line containing the while (...). Invalid read size 1 ...

Any one {

increases the indentation level by one, and any }

decreases the indentation level by one. No other indentation rules apply. I am assuming there are no curly braces in string literals.

char *indent(char *input, const char *pad)
{
    int lenpad = strlen(pad);
    int inlen = strlen(input);
    char *output = malloc(inlen+lenpad*90); //Here I'm praying +lenpad*90 is enough
    int indent = 0; 
    int i = 0;
    int j = 0;
    int ndx;
    int ondx;
    char current = 'a';
    int n;

    for(ndx=ondx=0; ndx<inlen; ndx++){
        current = input[ndx];
        if(current == '{') indent++;
        if(current == '\n'){
            output[ondx++] = '\n';
            n = ondx;
            while(input[n] != '\n' && input[n] != '\0'){ //Trying to check if the line to come has a curly bracket.
                if(input[n] == '}') //If it does, don't indent that line anymore.
                    indent--;
                n++;
            }
            for(j=0; j<indent; j++){
               for(i=0; i<lenpad; i++){
                output[ondx++] = pad[i];
                } 
            }
        }
        else{
            output[ondx++] = current;
        }
    }
    free(input);
    output[ondx] = '\0';
    return output;
}

      

Instead:

int main(void) {
    printf("asdfasdf\n");
    while (1)
    {
        while (2) {
            printf("printsomething\n");
        }
    }
}

      

My code gives:

int main(void) {
        printf("asdfasdf\n");
        while (1)
        {
            while (2) {
                printf("printsomething\n");
            }
            }
            }

      

+3


source to share


2 answers


In the decryption of the code you are trying to write, you must :

  • assimilate (not output) all leading spaces in the line (after \n

    )
  • replace them with the appropriate indentation calculated in the same way as the number {

    and}



Inject this and ask here if you can't get it to work

+2


source


Change your line

n = ondx;

      

to



n = ndx + 1;

      

You want to n

be the index of the next element in the input, not the output.

+2


source







All Articles