Reputation: 77
I have this program that I'm trying to modify it, but I don't understand why the statement: struct Link * temp = cap; doesn't print me the number that I assigned to the linked list. Thanks in advance!
struct Link
{
int data;
struct Link *urmatorul;
};
void Insert(Link * cap, int n)
{
struct Link * temp = (Link*)malloc(sizeof(struct Link));
temp->data = n;
temp->urmatorul = NULL;
if(cap != NULL)
temp->urmatorul = cap;
cap = temp;
}
void Print(Link * cap)
{
struct Link *temp = cap;
printf(" %d", cap->data);
printf("The number is: ");
while(temp != NULL)
{
printf(" %d", temp->data);
temp = temp->urmatorul;
}
printf("\n");
}
int main()
{
struct Link * cap;
cap = NULL;
printf("How many numbers? \n");
int x, n, i;
scanf(" %d", &x);
for(i = 0; i < x; ++i)
{
printf("Enter the number: \n");
scanf("%d", &n);
Insert(cap, n);
Print(cap);
}
return 0;
}
Upvotes: 1
Views: 38
Reputation: 3688
You need to pass the Link *
by reference to change it, that's a Link **
void Insert(Link **cap, int n)
{
struct Link * temp = (Link*)malloc(sizeof(struct Link));
temp->data = n;
temp->urmatorul = NULL;
if(*cap != NULL)
temp->urmatorul = *cap;
*cap = temp;
}
and in your main(...)
use
Insert(&cap, n);
or you could return the new Link *
from your Insert(...)
like this;
Link * Insert(Link * cap, int n)
{
struct Link * temp = (Link*)malloc(sizeof(struct Link));
temp->data = n;
temp->urmatorul = NULL;
if(cap != NULL)
temp->urmatorul = cap;
return temp;
}
and in your main(...)
use
cap = Insert(cap, n);
Upvotes: 2
Reputation: 726579
This line does not do anything, because cap
inside Insert
is a copy of cap
from the main
:
cap = temp;
The change gets discarded as soon as Insert
exits, so main
's cap
remains NULL
.
Change Insert
's signature to return Link*
, and assign it to cap
in the call from main
:
Link* Insert(Link * cap, int n)
{
struct Link * temp = malloc(sizeof(struct Link)); // No need to cast
temp->data = n;
temp->urmatorul = cap; // No need for the conditional
return temp;
}
The call looks like this:
cap = Insert(cap, n);
Upvotes: 1