如何遍历这个由多个结构、数组和指针组成的C数据结构?
我如何为(state--transition--to--label)给出一个值 我试过了,但失败了:如何遍历这个由多个结构、数组和指针组成的C数据结构?,c,pointers,memory-management,C,Pointers,Memory Management,我如何为(state--transition--to--label)给出一个值 我试过了,但失败了: typedef struct trans * Trans; typedef struct state{ int f; char label[20]; trans * TrasitionsArray[10]; }state; struct trans{ state * from; state * to; char label; }; voi
typedef struct trans * Trans;
typedef struct state{
int f;
char label[20];
trans * TrasitionsArray[10];
}state;
struct trans{
state * from;
state * to;
char label;
};
void main(){
state StatesArray[100];
}
您不能,因为您只分配了一个
state
s数组。state
结构有一个指向trans
数组的指针,但您从未分配该数组
在分配
StatesArray
数组的行之后,需要迭代该数组,并将内存和值分配给每个状态中的transitionarray
元素,您必须首先分配一些内存。未初始化指向数组的所有指针
strcpy(StatesArray[i].TrasitionsArray[j]->to->label,"blahblah");
inti,j;
结构状态[100];
对于(i=0;i<100;i++)
{
states.transitionsArray=(struct trans*)malloc(sizeof(struct trans)*10);
对于(j=0;j<10;j++)
{
//在此处设置“from”和“to”指针
}
}
顺便说一句:我想你的意思是struct trans*trasitionsArray代码>状态数组[100]代码>将仅为状态的结构成员分配内存。它将只为transitionArray
分配10*4个字节(指针大小为32位m/c),以容纳10个Transition
结构变量。但是内存没有分配给transition
结构变量的成员。对于from
和to
结构变量也是如此
使用下面的示例代码分配内部指针变量
int i, j;
struct state states[100];
for (i = 0; i < 100; i++)
{
states.transitionsArray = (struct trans*)malloc(sizeof(struct trans)*10);
for (j = 0; j < 10; j++)
{
// set 'from' and 'to' pointers here
}
}
inti,j;
结构状态[100];
对于(i=0;i<100;i++)
{
对于(j=0;j<10;j++)
{
StatesArray[i].TrasitionsArray[j]=(struct trans*)malloc(sizeof(struct trans));
StatesArray[i].TrasitionsArray[j]->from=(结构状态*)malloc(sizeof(结构状态));
StatesArray[i].TrasitionsArray[j]->to=(结构状态*)malloc(sizeof(结构状态));
}
}
注意:注意NULL
检查malloc
的返回值顺便说一句,我认为您指的是“转换”,而不是“转换”,恕我直言,我认为您需要花一些时间-从简单开始-使用内存分配和指针。
int i, j;
struct state states[100];
for (i = 0; i < 100; i++)
{
for (j = 0; j < 10; j++)
{
StatesArray[i].TrasitionsArray[j] = (struct trans*)malloc(sizeof(struct trans));
StatesArray[i].TrasitionsArray[j]->from = (struct state *)malloc(sizeof(struct state));
StatesArray[i].TrasitionsArray[j]->to = (struct state *)malloc(sizeof(struct state));
}
}