我正在嘗試使用給定結構為更大的專案實作鏈接串列。結構定義如下:
typedef struct node {
unint32_t size; // = size of the node
struct node * link; // = .next pointer
} * ListNode;
我能夠使用struct node *. 但是當我嘗試ListNode在以下程式中使用 like 時:
typedef struct node {
unint32_t size;
struct node * link;
} * ListNode;
void insert_node (ListNode * head, unint32_t size) {
ListNode new_node = (ListNode) malloc (sizeof(ListNode));
new_node->size = size;
new_node->link = NULL;
if (head == NULL) {
head = &new_node;
}
else {
ListNode current = *head;
while (current->link != NULL) {
current = current->link;
}
current->link = new_node;
}
}
int main (int argc, char const * argv[]) {
ListNode head = NULL;
insert_node (&head, 10);
insert_node(&head, 20);
ListNode ptr = head;
while (ptr != NULL) {
printf ("%d ", ptr->size);
}
printf ("\n");
return 0;
}
我得到一個分段錯誤。這是為什么?struct node *它甚至說ListNode是不兼容的指標/型別。我以為他們是一樣的struct,只是名字不同而已。
uj5u.com熱心網友回復:
一點澄清
typedef struct node {
unint32_t size;
struct node * link;
} *ListNode;
創建一個名為ListNode. 它是指向 a 的指標struct node。它不是一個struct node
所以當你這樣做時
sizeof(ListNode)
你得到一個指標的大小,而不是struct node
你需要做
sizeof(struct node)
一個很常見的事情是這樣
typedef struct node {
uint32_ size;
struct node* link;
} *PListNode, ListNode;
這創建了 2 種型別
- PlistNode 是一個指標
struct node - ListNode 是一個
struct node
“P”是一個提醒,這是一個指標
所以現在你可以做
PListNode pn = malloc(sizeof(ListNode));
uj5u.com熱心網友回復:
- 由于您向 提供
struct node**(aListNode*)insert_node,因此您需要取消參考它以分配給它。 - 你
malloc是 astruct node*(aListNode) 的大小,但你需要malloca 的大小struct node。 - 您還需要
ptr = ptr->link在main.
例子:
void insert_node(ListNode* head, uint32_t size) {
// corrected malloc, you don't want the sizeof a pointer but the
// size of a `node`:
ListNode new_node = malloc(sizeof *new_node);
new_node->size = size;
new_node->link = NULL;
if (*head == NULL) { // corrected check (dereference head)
*head = new_node; // corrected assignment
} else {
ListNode current = *head;
while (current->link != NULL) {
current = current->link;
}
current->link = new_node;
}
}
int main() {
ListNode head = NULL;
insert_node(&head, 10);
insert_node(&head, 20);
// the below loop had no exit condition before:
for(ListNode ptr = head; ptr; ptr = ptr->link) {
printf("%d ", ptr->size);
}
printf("\n");
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/430731.html
下一篇:復制派生類的類的建構式
