问题
Let's say I want to create structures in a loop. I don't want to change the values of the structure variables in each loop, I want to create new ones. However, from what I've learnt until know I have to name every new structure I make. Is there a way to do it without naming the structures?
And more specifically, can I have a pointer in each structure that will point to the next one?
What I wanna make is a BST and my struct is for every new node I add to the tree.That's how I've seen people do it, with struct. How can I add nodes if I don't name them? I definitely have some blanks there.
回答1:
You can use a struct variable many times in the loop by using malloc() to allocate memory for each iteration
#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
}
}
However if you know the number of struct s before hand you can create an array to hold the struct s
#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
}
}
回答2:
If I understood your question, answer is no, you can't declare a structure without a name. And regarding pointer to the next structure member, you should read more about lists and double linked lists in C here http://www.learn-c.org/en/Linked_lists
回答3:
Rules for an Identifier
- An Indetifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).
- The first character of an identifier can only contain alphabet( a-z , A-Z ) or underscore ( _ ).
- Identifiers are also case sensitive in C. For example name and Name are two different identifier in C.
- Keywords are not allowed to be used as Identifiers.
- No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to be used in or as Identifier.
So, to answer your question you cannot create new structs without identifying them, and even if you were able to, what would you reference it by? If there is nothing pointing to a it, it is simply garbage taking space on the memory
来源:https://stackoverflow.com/questions/43112121/create-structures-in-loop-without-naming-them