gpt4 book ai didi

在不命名的情况下循环创建结构

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:09 24 4
gpt4 key购买 nike

假设我想在循环中创建结构。我不想在每个循环中更改结构变量的值,我想创建新的。然而,从我所学直到知道我必须命名我制作的每个新结构。有没有办法在不命名结构的情况下做到这一点?

更具体地说,我可以在每个结构中都有一个指向下一个结构的指针吗?

我想做的是 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
}
}

但是如果你事先知道结构的数量,你可以创建一个数组来保存结构

#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
}
}

关于在不命名的情况下循环创建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43112121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com