简体   繁体   English

为什么 c++ 中的结构用作指针?

[英]why are the structs in c++ used as a pointer?

struct Node{
    int val;
    Node* next;
};

we use this struct as Node* node and not Node node.why?我们将此结构用作 Node* 节点而不是 Node 节点。为什么? any link to a reference would also be appreciated任何指向参考的链接也将不胜感激

I don't think so.我不这么认为。 This is sample for make a link list struct.这是制作链接列表结构的示例。 When you want to make a list with count of list is not defined.当您想制作一个未定义列表计数的列表时。 you can using struct: Node *next pointer.您可以使用 struct: Node *next 指针。 this pointer will be save address of next element of list.该指针将是列表下一个元素的保存地址。 So that, you can access next element from head element.这样,您就可以从 head 元素访问下一个元素。 if you use Node next;如果你接下来使用 Node; next is only a variable. next 只是一个变量。

The other comments already pointed this out, somewhat.其他评论已经在某种程度上指出了这一点。 When you define a struct, the compiler needs to know how much memory is needed to store an object of this new struct type.定义结构时,编译器需要知道存储这种新结构类型的对象需要多少内存。

However, if your struct contains another struct of the same type (direct or indirect) the compiler is unable to calculate the size needed for instantiating an object (understandably, since its size would vary depending on how many times this is chained).但是,如果您的结构包含另一个相同类型的结构(直接或间接),则编译器无法计算实例化对象所需的大小(可以理解,因为它的大小会根据链接的次数而有所不同)。

So in order to be able to allocate enough memory for an object, you need to use a pointer.所以为了能够为一个对象分配足够的内存,你需要使用一个指针。 The size of this pointer in memory is known at compile time (no matter where it points at, even if it is Null), so the compiler knows how much memory to allocate for each Node object you create.这个指针在内存中的大小在编译时是已知的(不管它指向哪里,即使它是 Null),所以编译器知道为你创建的每个 Node 对象分配多少内存。

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

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