我正在尝试使用iNode数组(我创建的结构(:
typedef struct iNode
{
int id;
int size;
int pointers[NUM_POINTERS];
} iNode;
我在这段代码中得到了segmentation fault
:
for (int k = 0; k < NUM_POINTERS-1; k++) {
root->pointers[k+1] = k+2;
iNode *inodes[maxiNodePerBlock];
for (int i = 0 ; i<maxiNodePerBlock; i++) {
iNode *tmp = malloc(sizeof(iNode));
tmp->id = -1;
tmp->size = -1;
for (int j= 0; j< NUM_POINTERS; j++) {
tmp->pointers[j] = -1;
}
strcpy(inodes[i], tmp);
free(tmp);
}
write_blocks(k+1, 1, inodes);
}
在strcpy(inodes[i], tmp);
线上。所以我尝试初始化它:
iNode *inodes[maxiNodePerBlock] = malloc(sizeof(iNode)*maxiNodePerBlock);
但随后我收到错误:variable-sized object may not be initialized
有什么建议吗?
strcpy(inodes[i], tmp);
当您到达上述行时, 没有为inodes[i]
分配内存 .您可以直接为inodes[i]
涂覆内存,而不是使用tmp
for (int i = 0 ; i<maxiNodePerBlock; i++) {
inodes[i] = malloc(sizeof(iNode));
inodes[i]->id = -1;
inodes[i]->size = -1;
for (int j= 0; j< NUM_POINTERS; j++) {
inodes[i]->pointers[j] = -1;
}