[英]array of struct pointers
我基本上是试图创建一个结构指针数组。 这些指针中的每一个都指向相同结构数组的另一个元素,即BLOCKS [2]。
到目前为止,这是我所做的。
typedef struct bb {
..
..
..
struct bb **successor;
} BLOCK;
BLOCK BLOCKS[10];
struct bb **A = malloc(sizeof(struct bb*)*5); //create an array of pointers of type struct bb, 5 units i.e A[0]->A[4].
BLOCKS[0].successors = A //just assigning
现在……如何将指针数组A的第一个元素分配给另一个结构?
我试过了:
A[0] = &BLOCKS[6];
它编译正常,但出现段错误。
您是否尝试过以下一种方法:
typedef struct bb {
..
..
..
struct bb *successor;
} BLOCK;
BLOCK BLOCKS[10];
struct bb *A = malloc(sizeof(struct bb)*5); //create an array of pointers of
type struct bb, 5 units i.e A[0]->A[4].
BLOCKS[0].successors = A[0];
因为在快速查看之后,我认为**应该呈现为*,并且您的malloc保留的内存不是针对5个结构的大小而是针对5个指向该结构的指针的大小。
来自问题的引言: “ 我基本上是在尝试创建结构指针数组。 ”
结构指针数组应为
BLOCK *ptrBlockArr[10]; //This an array of size 10, which can store 10 pointers to the structure BLOCK
现在,由于这些是指针,因此您将为每个元素分配内存。 这应该像
for(int i=0; i<10; i++)
{
ptrBlockArr[i] = (BLOCK *)malloc(sizeof(BLOCK));
}
您还提出了一个问题: “ 这些指针中的每一个都应该指向同一结构数组的另一个元素 ” 。 这可以像
for(int i=0; i<9; i++) // Run the loop till the last but one element
{
ptrBlockArr[i]->successor = ptrBlockArr[i+1];
}
//Assign the last's element's sucessor as the first element. This will make it circular. Check if this is your intention
ptrBlockArr[9]->successor = ptrBlockArr[0]
请注意,在您的结构中, successor
是struct bb**
,而应该是struct bb*
。
另外,您可以优化代码以将上面显示的两个循环组合为一个循环。 我将留给您自己学习和实施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.