c - Brainf**k interpreter problems -
i'm new c. i'm trying write brainfuck interpreter. have tried far.
#include <unistd.h> #include <stdlib.h> char *line; int curr_pos; void interprete(char *coms) { int a; int curr_loop; = -1; curr_loop = 0; while (line[++a]) line[a] = 0; = -1; while (coms[++a]) { if (coms[a] == '+') line[curr_pos]++; else if (coms[a] == '-') line[curr_pos]--; else if (coms[a] == '>') curr_pos++; else if (coms[a] == '<') curr_pos--; else if (coms[a] == '.') write(1, &line[curr_pos], 1); else if (coms[a] == '[') { if (line[curr_pos]) curr_pos++; else { curr_loop = 1; while (curr_loop) { ++a; if (coms[a] == '[') curr_loop++; else if (coms[a] == ']') curr_loop--; } } } else if (coms[a] == ']') { if (line[curr_pos]) { curr_loop = 1; while (curr_loop) { --a; if (coms[a] == '[') curr_loop--; else if (coms[a] == ']') curr_loop++; } } else curr_pos++; } } } int main(int ac, char **av) { if (ac == 2) { curr_pos = 0; line = malloc(sizeof(char) * 4096); interprete(av[1]); } write(1, "\n", 1); }
it works without loops ("[" , "]").when try "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
it gives me output
^b^a^h^h^k^b^q^k^n^h^@^c^@
expected output:
hello world!
i guess problems in following code-blocks:
else if (coms[a] == '[') { ... } else if (coms[a] == ']') { ... }
the program looking other bracket (and finds it), code-pointer additionally incremented in while
-statement (line 17). have decrement a
1
after search-loops. second problem is, increment data-pointer (curr_pos
)
if com[a] == '['
, line[curr_pos] != 0
and if com[a] == ']'
, line[curr_pos] == 0
you have increment code-pointer (a
) still automatically incremented in while
-statement. have pass in case. finally, don't have check @ both brackets if current cells value unequal zero. suggested code this:
else if (coms[a] == '[') { if (!line[curr_pos]) { curr_loop = 1; while (curr_loop) { ++a; if (coms[a] == '[') cur_loop++; else if (coms[a] == ']') cur_loop--; } a--; } } else if (coms[a] == ']') { // can jump opening bracket '[' // because program checks again , jumps behind // closing bracket if line[a] != 0 curr_loop = 1; while (curr_loop) { --a; if (coms[a] == '[') curr_loop--; else if (coms[a] == ']') curr_loop++; } a--; }
by way: try implement ',
'-command. makes brainfuck programs way more interesting ;)
Comments
Post a Comment