[英]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;
这是回报:
>Process removed: Current points to Nil, ProcTable value: Nil
我了解的是指针Current指向ProcTable中的值,但是当我尝试从表中“删除”该进程时,这些值正在更改,这些值被覆盖。 这是一个问题,因为那时我没有将死子进程的数据保存在其父列表中。
我该如何解决? 如何从阵列中“删除”进程而不会覆盖当前指向的数据?
ProcTable
是procs
的数组,因此在执行此操作时:
Current->parentProc->deadChildren = Current;
ProcTable[slot] = null;
您ProcTable[slot]
null
结构复制 到 ProcTable[slot]
覆盖旧的Current
,该Current
也覆盖Current->parentProc->deadChildren
因为它指向的是同一事物。
编辑:我想我现在明白了。 这必须是一项家庭作业。 您应该将阵列用作内存池,以便不必使用动态内存分配。 但是您仍然需要使用链表结构。 在这种情况下,当您需要“删除”一个proc并将其设为孩子时,只需重新拖动指针即可,但不要从数组中删除。
您的问题有点不清楚,但我会尽力回答。
首先,您的代码有错误:
strcpy(null.name, "Nil");
没有为null.name分配内存,因此这将导致错误(如果足够幸运的话)。
据我了解,您正在尝试做的是,在“删除”子进程时,将删除的进程的信息保留在其父级已死的子进程中。
我建议使用一个列表,因为显然该数组用于“活动”进程。 您不能仅指向数组,因为您对其所做的任何更改都会反映到指向该数组的指针。
然后,您可以在活动进程列表,进程的死子等之间移动列表节点。
即使在“删除”某个进程后,再也没有其他进程被“写入”到数组的位置,您也无法仅使用一个数组来维护deadChildren链。
我希望这有帮助。 如果不是,请指出其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.