[英]C Linked List from Array
在函數中,我創建了一個大小為2的數組,該數組將容納兩個PolyTerms。 然后,在函數中,我創建了一個列表。 之后,我想將數組元素作為鏈接列表傳遞到List中。
在if語句head-> next = nodePtr;后出現錯誤。 (訪問錯誤)。
謝謝。
我的部分代碼:
struct Fraction {
int num;
int denom;
};
struct PolyTerm {
int ex;
struct Fraction coe;
};
typedef struct PolyTerm PTerm;
typedef struct PolyTerm* PTermPtr;
struct PolyListNode {
PTermPtr termAddr;
struct PolyListNode* next;
};
typedef struct PolyListNode PList;
typedef struct PolyListNode* PNodeAddr;
typedef struct PolyListNode* PolyList;
PolyList sortPoly(void);
PolyList sortPoly() {
int arraySize = 2;
int i = 0;
//Array of PTermPtr. Each element holds ex, num and denom.
//Populating 2 elements for arrayTerm
PTermPtr arrayTerm;
arrayTerm = (PTermPtr) malloc(arraySize);
((arrayTerm) + 0)->ex = 2;
((arrayTerm) + 0)->coe.num = 2;
((arrayTerm) + 0)->coe.denom = 2;
((arrayTerm) + 1)->ex = 3;
((arrayTerm) + 1)->coe.num = 2;
((arrayTerm) + 1)->coe.denom = 2;
PNodeAddr nodePtr; //To create nodes
PolyList head = 0; //New List
PNodeAddr current; //To store Address of List Head
current= head; //Store address of head of list
while (i < arraySize) {
nodePtr = (PNodeAddr) malloc(sizeof(PList));
nodePtr->termAddr = (arrayTerm + i);
nodePtr->next = 0;
if (current == 0) {
head->next = nodePtr; //ERROR. Bad Access
} else {
while (current != 0) {
current = current->next;
}
current->next = nodePtr;
}
i++;
}
free (arrayTerm);
return head;
}
只需考慮一下代碼第一次通過循環會發生什么:
PolyList head = 0; //New List
Head現在為0(或null)。
current= head; //Store address of head of list
當前和磁頭現在為0
if (current == 0) {
它是。
head->next = nodePtr; //ERROR. Bad Access
嘗試訪問為0且為null的head。 您正在訪問null
還應注意,傳遞給malloc的大小是錯誤的。 您傳入的是要創建的陣列的大小,而不是所需的內存大小。
例如,您需要一個mytype類型的2元素數組,您需要此代碼:
newarray = malloc(2 * sizeof(mytype));
然后
newarray[0]
和
newarray[1]
有空間容納mytype。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.