假设我想在循环中创建结构。我不想更改每个循环中结构变量的值,我想创建新的。然而,根据我所学到的知识,我必须命名我所做的每一个新结构。有没有一种方法可以在不命名结构的情况下做到这一点?
更具体地说,我可以在每个结构中都有一个指向下一个结构的指针吗?
我想要制作的是 BST,我的结构适用于我添加到树中的每个新节点。这就是我看到人们使用结构来做到这一点的方式。如果我不命名节点,如何添加节点?我那里肯定有一些空白。
您可以通过使用 malloc() 为每次迭代分配内存,在循环中多次使用结构变量
#include<stdio.h>
#include<stdlib.h>
struct structname
{
int a;
struct structname* b; //points to next struct
};
int main()
{
struct structname* ptr[10]; //
for(int i=0; i<10; i++)
{
ptr[i] = (struct structname*)malloc(sizeof(struct structname));
ptr[i]->a=1;
ptr[i]->b=NULL; //point to next struct instead of NULL
}
}
但是,如果您事先知道 struct 的数量,则可以创建一个数组来保存 struct
#include<stdio.h>
#include<stdlib.h>
struct structname
{
int a;
};
int main()
{
struct structname array[10];
for(int i=0; i<10; i++)
{
array[i].a = 1; //input number here
//no need of pointing to next struct as its already in an array
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)