定义一个成员指向另一个成员的结构

定义一个成员指向另一个成员的结构

本文介绍了定义一个成员指向另一个成员的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 C 对网络进行编程.我有相互链接的节点,我想通过使 struct 成员指向另一个成员(而不是另一个节点,因为我想保留链接的身份).我这样做的代码是这样的:

I'm trying to program a network in C. I have nodes which are linked to each other and I 'd like to do that by making the struct member point to another member (not to another node, because I want to preserve the identity of the links).The code I made to do that is something like:

struct node{
    int k; //number of links
    struct node.link **link; //<- wrong
};

但这不正确,因为节点不是变量而是变量类型(这已经在另一个 QA 中作为错误进行了讨论:首先您必须定义节点类型的变量,然后应用 .link,但是这在这里没有帮助).还有一个称为结构成员指向另一个结构成员"的 QA,但他们不是从定义中做到这一点的,并且不太清楚如何概括它(至少对我而言).

but this is not right as node is not a variable but a type of variable (this is already discussed as an error in another QA: first you have to define a variable of node type and then apply the .link, but this doesn't help here). There's also a QA called "Struct member point at another struct member" but they don't do it from definition and it is not so clear how to generalize it (at least for me).

这样做是否正确?

推荐答案

好的,这就是我最终在我的程序中解决它的方法:

Ok, this is how I finally solved it in my program:

typedef struct node{
int k; //connectivity
struct link **enlace; //vector of LINKs
}NODE;

typedef struct link{
NODE *node1;
NODE *node2;
}LINK;

基本上,我定义了两个结构体:一个是NODE类型,它包含节点和LINK向量的连接方式的信息,另一个是结构LINK,它包含链接本身的信息,我的意思是链接连接哪些节点.

Basicly, I defined two structures: one is the NODE type, which contains the information of how connected is the node and a vector of LINKs, and the other is the structure LINK which contains the information of the link itself, I mean which nodes the link connects.

通过这两个,我能够创建具有遵循泊松分布的连通性的节点网络,然后一个接一个地销毁每个链接,从列表中随机选择一个链接,然后将每个节点的指针重定向到空.

With these two I'm able to create the network of nodes with a connectivity following a Poisson distribution, and then destroy each link one by one, choosing one link at random from a list and then redirecting the pointers of each node to NULL.

这篇关于定义一个成员指向另一个成员的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 06:01