简体   繁体   English

C 中的结构体、指针和树

[英]Structs, pointers, and trees in C

For our final semester project, everyone in my Operating Systems class has been tasked with implementing a pseudo "linux filesystem".对于我们最后一个学期的项目,我的操作系统 class 中的每个人都负责实现一个伪“linux 文件系统”。 The idea is to simulate handling files, folders, changing directories, and so forth.这个想法是模拟处理文件、文件夹、更改目录等。

I dislike having to work with Strings and pointers when I program in C, and unfortunately for my peace-of-mind, this project looks to involve both.当我在 C 中编程时,我不喜欢使用字符串和指针,不幸的是,为了我的安心,这个项目看起来涉及两者。 Because I am relatively uncomfortable with pointers, I was hoping I could get a sanity check that my backend implementation of the underlying tree structure is sound.因为我对指针比较不适应,所以我希望我能对我的底层树结构的后端实现进行健全的检查。

typedef struct floorNode
{
    char floorName[30]; //the name of the tree node
    struct floorNode *parentPointer; //this is a pointer to the parent node. Null for the root node.
    struct floorNode *childPointers[10]; //this is an array holding pointers to up to 10 child nodes. 
    char fileArray[10][30]; //this is an array of 10 'files', each of up to length 30.
                            //for this assignment, strings are the only type of "file"

} floorNode;

Is this the proper way to implement a tree in C?这是在 C 中实现树的正确方法吗?

That is more or less the proper data type.这或多或少是正确的数据类型。

I'm concerned about fileArray[][] .我担心fileArray[][] I don't think it is needed, unless I'm misunderstanding its purpose.我认为不需要它,除非我误解了它的目的。 To get floorName of the children, instead traverse childPointers[] to obtain the name in the children.要获取孩子的floorName ,请改为遍历childPointers[]以获取孩子中的名称。

Something to consider if the nodes have 30 character strings is to make the storage for all of them a little bigger, 31 in this case, so that a trailing NUL is always present and no special yucky handling is needed to distinguish between a 30-character string without a NUL and all the shorter strings which have one.如果节点有 30 个字符串,需要考虑的是让所有节点的存储空间更大一点,在这种情况下为 31,以便始终存在尾随 NUL,并且不需要特殊的令人讨厌的处理来区分 30 个字符没有 NUL 的字符串和所有具有 NUL 的较短字符串。

You probably want a linked list of children.你可能想要一个孩子的链接列表。 You definitely don't want arrays of pointers for this.您绝对不希望为此使用 arrays 指针。 You should also think about how to know if a file is actually a directory.您还应该考虑如何知道文件是否实际上是目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM