如何正确使用结构内的指针数组 [英] How to use an array of pointers inside a structure correctly
问题描述
我有两个结构parent和child,如下面的代码所示.父结构具有一个类型为child的指针数组.程序进入for循环时出现隔离错误.我的代码有什么问题吗?我不想使用方括号的原因是,我有一个函数采用了child类型的指针参数,并且我希望将每个子指针传递给该函数而无需使用&.
I have two structures parent and child as you can see in my code below. The parent structure has an array of pointers of type child. I get a segmetation error when the the program enters the for loop. Is there any thing wrong in my code? The reason why I don't want to use square brackets is that I have a function that takes a pointer parameter of type child and I want to pass every child pointer to that function without the need to use &.
任何帮助将不胜感激谢谢
Any help would be appreciated Thank you
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int id;
} child;
typedef struct {
child** c;
} parent;
int main(int argc, char **argv) {
int number_of_children = 5;
parent* p = (parent*)malloc(sizeof(parent));
p -> c = (child **) malloc(number_of_children * sizeof(child*));
int i;
for(i=0; i<number_of_children; i++)
p -> c[i] -> id = i;
}
推荐答案
您正在正确分配子代指针表,但未分配任何子代.
You are correctly allocating the children pointer table but you're not allocating any child.
int i
for(i = 0; i < number_of_children; ++i) {
p->c[i] = (child *) malloc(sizeof(child));
p -> c[i] -> id = i
}
这篇关于如何正确使用结构内的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!