在不覆盖指针指向的值的情况下取消 C 中结构数组的索引

Nullify an index of a struct array in C without overwriting values pointed to by pointer

为了方便阅读,本代码在实际版本中进行了简化,实际代码包含大量头文件,体积庞大。

我有一个结构(进程)数组,我有一个 Current 指针,定义如下。我想从数组中删除一个过程:

typedef struct proc proc;
typedef stuct proc *procPtr;

struct proc{
   procPtr nextProc;
   procPtr parentProc;
   procPtr deadChildren;
   char *name;
   int pid;
};

int slot = 0 // the slot to operate on in the table
proc ProcTable[MAX];
procPtr Current;
proc null;

null.nextProc = NULL;
null.parentProc = NULL;
null.deadChildren = NULL;
strcpy(null.name, "Nil");
null.pid = -1;

/*Some code, table is populated with null procPtr*/

strcpy(ProcTable[slot].name, "Proc2");
ProcTable[slot].nextProc = NULL;
ProcTable[slot].deadChildren = NULL;
ProcTable[slot].parentProc = Current;
ProcTable[slot].pid = 2;

/* Some code, Current proc is switched to child and quitting*/
Current = &ProcTable[slot];

/* Remove the process from the table */
Current->parentProc->deadChildren = Current;
ProcTable[slot] = null;

printf("Process removed: Current points to %s,
       ProcTable value: %s", Current->name, ProcTable[slot].name);

return;

这是return:

>Process removed: Current points to Nil, ProcTable value: Nil

我的理解是 Current 指针指向 ProcTable 中的值,但是当我尝试从 table "remove" 进程时,值正在被更改,这些值正在覆盖。这是一个问题,因为那时我没有在其父列表中保存死掉的子进程的数据。

我该如何解决这个问题?我怎样才能 "remove" 从数组中处理而不覆盖当前指向的数据?

ProcTableprocs的数组,所以当你这样做的时候:

Current->parentProc->deadChildren = Current;
ProcTable[slot] = null;

您正在 复制 null 结构 ProcTable[slot] 覆盖旧的 Current也会覆盖 Current->parentProc->deadChildren 因为它指向相同的东西。

编辑: 我想我现在明白了。这必须是家庭作业。您应该将数组用作内存池,以免必须使用动态内存分配。但是您仍然需要使用链表结构。在这种情况下,当您需要 'remove' 一个过程并使其成为子过程时,只需重新调整指针,但不要从数组中删除。

你的问题有点不清楚,我会尽量回答的

首先,你的代码有错误:

strcpy(null.name, "Nil");

没有为null.name分配内存,所以这会导致错误(如果你足够幸运的话)。

据我所知,您正在尝试做的是,当 child 为 "removed".

我建议使用列表,因为数组显然用于 "active" 进程。您不能只指向数组,因为您对它所做的任何更改都会反映到指向它的指针上。

然后你可以在活动进程列表中移动列表节点,一个进程的死 children 等等。

即使在一个进程 "removed" 之后没有其他进程会 "written" 在数组的某个位置,您也无法仅用一个数组来维护 deadChildren 链。

希望对您有所帮助。如果没有,请指出进一步的问题。