CSC*_*SCS 3 c scheme interpreter pointers
我是C的新手,我目前正在C中实现一个Scheme解释器.我已经接近尾声但是一个问题困扰着我,我还没能解决.
我想要一个指向结构的"globalEnvironment"指针,该结构在程序运行期间保持不变并且也被修改(不是常量).
/****************************************************************
Creates the List as a pointer to the conscell structure
*/
typedef struct conscell *List;
/****************************************************************
Creates a conscell structure, with a char pointer (symbol) and two pointers to
* conscells (first and rest)
*/
struct conscell {
char *symbol;
struct conscell *first;
struct conscell *rest;
};
List globalEnvironment;
/****************************************************************
Function: globalVariables()
--------------------
This function initializes the global variables
*/
void globalVariables() {
globalEnvironment = malloc(sizeof (struct conscell));
globalEnvironment->symbol = NULL;
globalEnvironment->first = NULL;
globalEnvironment->rest = NULL;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,"List"是指向conscell结构的指针.所以我想要的是globalEnvironment列表是全局的.
问题是我不能在那里做malloc.如果我尝试以下方法:
List globalEnvironment = malloc(sizeof (struct conscell));
Run Code Online (Sandbox Code Playgroud)
而不仅仅是"List globalEnvironment;" 它给出了"初始化元素不是常量"的错误
为了解决这种情况,我创建了一个新函数"globalVariables",它在程序开始时运行,初始化globalEnvironment并分配内存.它没有像我预期的那样工作,并且我一直在为其他函数获取分段错误错误,我没有写到这里以保持简单.
是否有另一种更简单的方法来向C中的结构声明指针(非常量)?
希望有人可以提供帮助,谢谢
看起来malloc你应该尝试使用全局数据.你可以试试
struct conscell globalEnvironment;
Run Code Online (Sandbox Code Playgroud)
只记得永远不要free.
如果你需要一个指针句柄,那么你可以推送列表上的单元格:
struct conscell _globalEnvironment;
List globalEnvironment = &_globalEnvironment;
Run Code Online (Sandbox Code Playgroud)
不过,记住永远不要free _globalEnvironment.