我正在尝试用 C 语言编写图灵机代码。 但我的程序不起作用,它陷入了无限循环。 这是我的代码和一些解释:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3 //number of different states for the cells
#define K 20 //length of the tape
typedef struct
{
int state;
int head;
char tape[];
}mt; //machine
void init_mt(mt* machine, char val[], int n)
{
machine->state=1; //edited mistake
machine->head=0; // edited mistake
int i;
for(i=0;i<n;i++)
{
machine->tape[i]=val[i];
}
}; //initialization of a machine
typedef struct
{
char write;
char direction;
int state;
}actions; //actions composed of three instructions
typedef struct
{
actions exec01;
actions exec02;
actions exec11;
actions exec12;
}program; //program composed of four actions
void execute(actions exec, mt mach)
{
mach.tape[mach.head] = exec.write;
mach.state = exec.state;
if(exec.direction == 'R')
{
mach.head++;
}
else
{
mach.head--;
}
} //class that follows the instructions from the actions
void execute2(mt mach, program p)
{ do{
printf("%c %d %d \n", mach.tape[mach.head], mach.head, mach.state );
if(mach.tape[mach.head] == 0)
{
if(mach.state == 1)
{
execute(p.exec01, mach);
}
else if(mach.state == 2)
{
execute(p.exec02,mach);
}
}
else if(mach.tape[mach.head] == 1)
{
if(mach.state == 1)
{
execute(p.exec11,mach);
}
else if(mach.state == 2)
{
execute(p.exec12,mach);
}
}
}while( (mach.head<K) && (mach.state != 3));
} // class that read the program and act according to the states of the cells,
//keeps going until the machine is at the third state or if it reaches the end of the tape
int main(){
mt machine;
char t[10]={'1','1','1','0','0','1','0','1','0','1'};
init_mt(&machine, t, 10);
program p ={ {'0','R',1}, {'0','R',1}, {'1','R',2}, {'0','L',3} };
execute2(machine, p);
return 0;
} //main with a tape composed of 10 cells and a program composed of four actions
这个程序一直无限期地显示“0,0,1”,我找不到错误。 感谢您的帮助,如果不清楚,我们深表歉意。
最佳答案
这里有一些问题:
在某些情况下,您将结构作为参数传递,而不是指向它们的指针。这会在被调用函数中创建整个结构的本地副本。当函数返回时,对这些副本所做的任何更改都将丢失。这也是低效的。只需传递结构指针。
您没有在结构中为
tape
声明任何空间,因此它基本上是一个零长度数组。任何类型的访问都会破坏内存并导致未定义的行为。您在这里有几个选择。您可以为其选择一些固定大小,并将其用作数组大小,也可以将其更改为指针并为其动态分配存储空间。不管怎样,您必须分配存储空间。在
execute2
中,它将mach.tape[mach.head]
与整数0
和1
。但磁带不包含这些值。它包含字符'0'
和'1'
。因此,请用单引号将这些常量引起来。如果遇到意外值,打印错误也是一个好主意。那会立即发现这个问题。
关于C 图灵机无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36903554/