I wrote this C code from a pointers practice video and the problem I am having is that after integrating head as a local main variable over a global variable declared before main(), the program is no longer entering the for loop and I can't seem to figure out why.
The interesting part is that I delete the head=NULL, the loop seems to be executing. Does anyone know where the problem with assigning NULL to head is?
Here is my code:
#include <stdlib.h>
#include <stdio.h>
struct Node{
int data;
struct Node* next;
};
struct Node* Insert(struct Node* head, int data){
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
(*new_node).data = data;
(*new_node).next = head;
head = new_node;
}
void Print(struct Node* head){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp = head;
while(temp!=NULL){
printf("%d", (*temp).data);
temp = (*temp).next;
}
printf("\n");
}
int main(){
struct Node* head = NULL;
int n, i, x;
printf("%s", "How large do you want your array to be?\n");
scanf("%d", &n);
for(i; i<n; i++){
printf("Enter a number:\n");
scanf("%d",&x);
head = Insert(head, x);
Print(head);
}
return 0;
}