[英]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.