我坐下来试着实现BrainFuck。语法看起来相当简单。我很难让这件愚蠢的事情开始工作。我已经干了很长一段时间了,我承认我需要睡觉。也许这就是问题所在。翻译没有输出任何东西。我很确定这个问题很简单;我知道在我更好地掌握这个程序的方向之后,我需要对一些函数调用进行模块化。为什么我没有输出?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <memory.h>
#include "list.h"
node file;
node flow;
node memm;
void init() {
file.val = 1;
file.next = 0;
flow.val = 1;
flow.next = 0;
memm.val = 1;
memm.next = 0;
}
int run = 1;
void quit(int val) {
run = 0;
while (file.next) pop(&file);
while (flow.next) pop(&flow);
while (memm.next) pop(&memm);
}
void doop() {
switch (file.val++) {
case '>':
memm.val++;
break;
case '<':
memm.val--;
break;
case '+':
get(&memm, memm.val)->val++;
break;
case '-':
get(&memm, memm.val)->val--;
break;
case '.':
printf("c", get(&memm, memm.val)->val);
fflush(stdout);
break;
case '[':
if (!get(&memm, memm.val)->val)
while (get(&file, file.val)->val != ']')
file.val++;
else push(&flow, file.val);
case ']':
if (get(&memm, memm.val)->val)
file.val = pop(&flow);
}
}
int main(int argc, char** argv) {
int flen, c, i, f_len;
FILE *fh;
char fh_name[] = "test";
signal(SIGINT, quit);
init();
fh = fopen(fh_name, "r");
while (run && (c = fgetc(fh)) != EOF)
push(&file, c);
fclose(fh);
f_len = length(&file);
while (file.val > 0 && file.val < f_len)
doop();
return (EXIT_SUCCESS);
}list.h
struct node {
int val;
struct node *next;
};
typedef struct node node;
int length(node *n);
void push(node *n, int i);
int pop(node *n);
node *get(node *n, int i);list.c
#include <stdlib.h>
#include "list.h"
int length(node *m) {
int len = 0;
while (m->next) {
len++;
m = m->next;
}
return len;
}
void push(node *n, int i) {
node *m = n;
while (m->next)
m = m->next;
m->next = malloc(sizeof(struct node));
m->next->val = i;
m->next->next = 0;
}
int pop(node *n) {
node *m = n;
int i = length(n) - 1;
while (i) {
i--;
m = m->next;
}
i = m->next->val;
free(m->next);
m->next = 0;
return i;
}
node *get(node *n, int i) {
node *m = n;
while (i) {
i--;
if (!m->next)
push(n, 0);
m = m->next;
}
return m;
}test是BrainFuck的“你好世界”
Hello World program
>+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-]
<.#>+++++++++++[<+++++>-]<.>++++++++[<+++>-]<.+++.------.--------.[-]>++++++++[
<++++>-]<+.[-]++++++++++.发布于 2015-03-06 21:31:09
线
switch (file.val++) {不可能是对的。目前,它只是在增量文件链的第一个"val“,比如它下面的"mem.val++”。
我希望您将需要去掉该行上的++,然后对增加指向指令的指针而不是指令本身做一些事情。
你的“]指令是错误的;即使你不打算回去,你也需要做流行音乐。”
你的“指示”部分是错误的。如果该值从零开始,它当前将跳到第一个‘它找不到匹配的’]。
发布于 2015-03-06 21:09:23
因为你需要睡觉,也因为你的代码乱七八糟,我发现
printf("c", get(&memm, memm.val)->val);它将打印一个c,仅此而已,应该是
printf("%c", get(&memm, memm.val)->val);
/* ^ it's the format specifier for the argument */,我怎么这么快就找到这个的?
BTW:get(&memm, memm.val)->val是非常糟糕的风格,但真的很糟糕。
https://stackoverflow.com/questions/28907511
复制相似问题