#include<stdio.h>
#include<malloc.h>
int main()
{
int count = 0;
int size = 0;
printf("Enter the number of plants\n");
scanf("%d",&size);
printf("Enter the amount of pesticide each plant has.\n");
You have to allocate the memory for each node inside the while loop. If you like to add the new node at the end of the list notice the end of the list by a pointer to the pointer at the end of the list. Apart form this you have to pass the addres of the value to be read to scanf:
struct plants * head = NULL;
struct plants ** current = &head; // current refers there, where next node has to be placed
while( count < size ) // do it for "size" nodes
{
*current = malloc(sizeof(struct plants)); // allocate memory for the node right to target
scanf( "%d", &((*current)->val)); // read the data
(*current)->next = NULL; // node is last node in list, so its successor is NULL
current = &((*current)->next); // step on forward
count ++; // increment number of nodes
}
Note since the type of current is struct plants ** this codes puts the new node to head for the first element of the list and to (*current)->next for all further nodes of the list.
It would be easier to add the new node at the head of the list:
struct plants * head = NULL; // init head with NULL (this becomes end of the list)
while( count < size ) // do it for "size" nodes
{
struct plants * current = malloc(sizeof(struct plants)); // allocate memory for the node
scanf( "%d", ¤t->val); // read the data
current->next = head; // successor of node is head
head = current; // new node is head of list
count ++; // increment number of nodes
}
This will print your list:
struct plants *temp = head;
while( temp != NULL )
{
printf( "%d ", temp->val );
temp = temp->next;
}
Don't forget to free the list at the end of your program:
while ( head != NULL )
{
struct plants *next = head->next;
free( head );
head = next;
}
return 0;
}
currentis null when you start the loop, as the reason it won't even enter your loopcurrentpoint to head. As it is not pointing at anything when loop starts. And you have to allocate memory for every new node as loop iterates.struct plants* head = NULL;head = malloc(sizeof(struct plants)); struct plants* current= head;