因此,我今天開始學習C,沒有任何問題通過補習練習,但我終於被卡住了。我檢查了stackoverflow,其他reddit帖子和youtube視頻。我正在嘗試創建一個鏈表。以下是我的代碼,詳細說明了我認爲代碼的作用。當我在CLion中運行它時,printList函數沒有輸出。但是,如果我取消註釋掉被削減的行(只有3行很容易找到),並且將我的調用註釋爲push(),printList函數會打印1,因爲它應該是這樣。據我瞭解,3條註釋行和push()中的行是做同樣的事情,那麼爲什麼輸出不同呢?更改指針值的問題
#include <stdio.h>
#include <malloc.h>
typedef struct node {
int val;
struct node *next;
} node_t; //node struct is defined
void printList(node_t *head); //printlist function is initialized, accepts a node_t pointer (correct vocabulary?)
void push(node_t *head, int val); //push function is initialized
int main() {
node_t *head = NULL; //a pointer is created that points to a struct of type node_t, and currently points to NULL
push(head, 1); //push function accepts node_t pointer which currently points to NULL, and an int: 1
// head = (node_t *) malloc(sizeof(node_t)); //the pointer "head" now points to a section of memory that can
//hold a node_t struct
// head->val = 1; //head's "val" variable now points to the int 1
// head->next = NULL; // head's "next" variable now points to NULL
printList(head);
return 0;
}
void printList(node_t *head) {
node_t *current = head;
while (current != NULL) {
printf("%d ", current->val);
current = current->next;
}
}
void push(node_t *head, int val) {
node_t *current = head; //the pointer "current" now points to the value that head pointed to (NULL)
current = (node_t *) malloc(sizeof(node_t)); //just enough memory is allocated for a node_t struct,
// and the variable current now points to it
current->val = val; //current's "val" variable now points to the int "val" from the function parameters
current->next = NULL; //current's "next" variable, which is a node_t pointer, now points to NULL
}
你不改變*頭*了'push'之外; 'push'中的'head'是一個局部變量。 –
問題的一個部分:您直接在'current = malloc(...)'之後執行'current = head'。現在,第二次作業後的「current」點在哪裏? –
問題的另一部分:搜索*模擬c *中的引用傳遞。 –