c - 如何遍历这个由多个结构体、数组和指针组成的 C 数据结构?

标签 c pointers memory-management

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---trasition---to---label)赋值

我尝试过但失败了:

strcpy(StatesArray[i].TrasitionsArray[j]->to->label,"blahblah");

最佳答案

state StatesArray[100]; 仅为状态的结构成员分配内存。它只会为 TrasitionsArray 分配 10 * 4 字节(32bit m/c 中的指针大小)来保存十个 Transition 结构变量。但是没有为 transition 结构变量的成员分配内存。对于 fromto 结构变量也类似。

使用下面的示例代码来分配内部指针变量。

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));
    }
}

注意:请注意 NULL 检查 malloc 的返回值

关于c - 如何遍历这个由多个结构体、数组和指针组成的 C 数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11129071/

相关文章:

c++ - 为什么我应该在 scanf() 系列成员中加入一个长度修饰符作为参数?有什么好处?带有长度修饰符的 scanf 有什么作用?

c - 需要一个具有打印屏幕功能的winapi函数

c++ - 指针函数

c++ - 访问冲突写入位置 0x00000000。指针问题

delphi - FreeMM 与 ShareMem

c - 段错误(核心转储) C 编程 pthreads 直方图

c - 我如何始终包含静态库中的符号?

c - 如果 &a 生成 a 的地址,它如何成为指向 a 的指针?

c - Rust C 互操作段错误(斜线 STATUS_ACCESS_VIOLATION)

ios - ScrollView 太慢——内存管理问题?