我的目标是编写一个C程序,对给定的
char *input
进行缩进。一级缩进的样式在字符串const char *pad
中给出。我写了下面的代码,在我的头脑中可以工作,但在实践中却不能。肯定有哪里出错了,但我找不到它。
另外,我想不出为什么Valgrind不喜欢包含while(...)的那一行。Invalid read of size 1...
任何一个{
都会使缩进级别增加一级,而任何一个}
都会将缩进级别减少一级。不应用其他缩进规则。我假设字符串字面值中没有花括号。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;
}
改为:
int main(void) {
printf("asdfasdf\n");
while (1)
{
while (2) {
printf("printsomething\n");
}
}
}
我的代码输出:
int main(void) {
printf("asdfasdf\n");
while (1)
{
while (2) {
printf("printsomething\n");
}
}
}
indent--;
这一行(在条件语句内部)设置断点,我们可以看到 这一行 从未被执行。 - user12205