简体   繁体   English

如何初始化结构中的结构指针?

[英]How to initialize structure pointers in a structure?

typedef struct cpu{
    process_t** cpu;
    int cpu_id;
    int queue_len;
}cpu_t;

If I want to initialize this struct:如果我想初始化这个结构:

cpu_t** cpus = malloc(sizeof(cpu_t*)*num_processors);

int i = 0;



for(i=0;i<num_processors;i++){
    cpus[i]->cpu_id = i;

    cpus[i]->queue_len = 0;
    
    cpus[i]->cpu = malloc(sizeof(process_t*)*num_process);
    
    printf("test\n");
}

The "test" will not appear and my program seems to stop after this. “测试”不会出现,我的程序似乎在此之后停止。

You allocated an array of uninitialized pointers您分配了一组未初始化的指针

cpu_t** cpus = malloc(sizeof(cpu_t*)*num_processors);

Thus the subscript operator returns such an uninitialized pointer as for example in this statement因此,下标运算符返回这样一个未初始化的指针,例如在这个语句中

cpus[i]->cpu_id = i;

and using such a pointer to access memory invokes undefined behavior.并且使用这样的指针来访问 memory 会调用未定义的行为。

Maybe actually you need something like the following也许实际上您需要以下内容

cpu_t *cpus = malloc( sizeof( cpu_t ) );

cpus->cpu = malloc( sizeof( process_t * ) * num_process );
//...

Pay attention to that using the same name cpu for different entities as in this structure definition注意这个结构定义中不同实体使用同名cpu

typedef struct cpu{
    process_t** cpu;
    //..

only confuses readers of the code.只会让代码的读者感到困惑。

When you do this:当你这样做时:

cpu_t** cpus = malloc(sizeof(cpu_t*)*num_processors);

You're allocating space for an array of pointers to cpu_t .您正在为指向cpu_t的指针数组分配空间。 These pointers have not been initialized, however.但是,这些指针尚未初始化。 Then later you attempt to dereference these pointers:然后稍后您尝试取消引用这些指针:

cpus[i]->cpu_id = i;

Dereferencing an uninialized pointer triggers undefined behavior .取消引用未初始化的指针会触发未定义的行为

It seems that you don't actually want an array of pointers to cpu_t , but an array of cput_t .似乎您实际上并不想要一个指向cpu_t的指针数组,而是一个cput_t数组。 You can create such an array like this:您可以像这样创建这样的数组:

cpu_t *cpus = malloc(sizeof(cpu_t)*num_processors);

Then you can access each array element using .然后,您可以使用 访问每个数组元素. instead of -> .而不是-> You'll want to make a similar change to the cpu member of cpu_t to create an array of those:您需要对cpu_tcpu成员进行类似的更改,以创建一个数组:

typedef struct cpu{
    process_t *cpu;
    int cpu_id;
    int queue_len;
}cpu_t;

...

for(i=0;i<num_processors;i++){
    cpus[i].cpu_id = i;
    cpus[i].queue_len = 0;
    cpus[i].cpu = malloc(sizeof(process_t)*num_process);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM