I have written a simple brainfuck interpreter in c. all the commands work fine, except for loops. currently, I am handeling them like this:
I have a function to find the matching square bracket:
int findbracket(char *commands, int currentpos){
int lb = 0;
int rb = 0;
for(int i = currentpos; i != strlen(commands); ++i){
if(commands[i] == '[') ++lb;
if(commands[i] == ']') ++rb;
if(lb == rb){
return i;
}
}
}
and the I have a stack to keep track of all the brackets:
void interpret(char *commands){
int stack[10];
int top = 0;
for(int i = 0; i < strlen(commands); ++i){
char command = commands[i];
//other commands...
else if(command == '['){
if(*ptr == 0){
i = findbracket(commands, i);
}
else{
stack[top] = i;
++top;
}
}
else if(command == ']'){
if(*ptr != 0){
i = stack[top];
}
else{
--top;
}
}
}
}
however, this doesn't seem to work. for example, when executing hello world: ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
it gives no output at all. what am I doing wrong?
You want:
if(*ptr != 0){
i = stack[top-1];
}
"top" marks where the next thing will go on the stack, just above where the last thing was added.