我必須做一個鏈接列表程序,有很多功能,比如刪除,添加和修改數字。我的功能不記憶鏈接列表頭
在我的代碼中,當我在選擇1的函數中放入一個數字後,當我想要顯示所有數字時,我將頭放在參數中,但是在Visual Studio中看到函數的參數don'沒有任何東西。我可以做的,以傳遞參數鏈表的頭,我的功能Displaynbr
#include <stdio.h>
#include <stdlib.h>
struct Mynbr
{
int nbr;
struct Mynbr* next;
} typedef Mynbr;
void Menu();
void choiceMenu(int choice, Mynbr* first);
Mynbr* Addnumber(Mynbr* first);
void Displaynbr(Mynbr* first);
int main(void)
{
Mynbr* head = NULL;
int choice = 0;
while (choice!=5)
{
Menu();
printf("Your choice : "); scanf("%d", &choice);
choiceMenu(choice, head);
}
system("PAUSE");
return 0;
}
void Menu()
{
printf("\n1.Add number to the list\n");
printf("2.Delete number from the list\n");
printf("3.Search number in the list\n");
printf("4.Display all the numbers from the list\n");
printf("5.Exit\n");
}
void choiceMenu(int choice, Mynbr* first)
{
switch (choice)
{
case 1:
Addnumber(first);
break;
case 2:
break;
case 3:
break;
case 4:
Displaynbr(first);
break;
case 5:
break;
}
}
Mynbr* Addnumber(Mynbr* first)
{
printf("\n===Function to add a number===\n");
Mynbr* head_nbr = first;
if (!head_nbr)
{
head_nbr = (Mynbr*)malloc(sizeof(Mynbr));
printf("Enter a number :"); scanf("%d", &(head_nbr->nbr));
head_nbr->next = NULL;
}
return head_nbr;
}
void Displaynbr(Mynbr* first)
{
printf("\n===Function to display number===\n");
Mynbr* curr = first;
if (curr->next)
{
printf("The number is : %d", curr->nbr);
Displaynbr(first->next);
}
}
C11草案標準n1570:* 6.5.2.2函數調用4參數可以是任何完整對象類型的表達式。在爲函數調用 做準備時,將對參數進行評估,併爲每個參數分配相應參數的值。 93)函數可能會改變其參數的值,但這些改變不會影響參數的值。* tl; dr:C是按值傳遞的值。 – EOF
題外話:你不需要投入malloc的返回 – sokkyoku