Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main() {
typedef struct element {
	int val;
	struct element * next;
}list;
list * addEl(list * l, int x){
	list * tmp;
	tmp=malloc(sizeof(list));
	tmp->val=x;
	tmp->next=1;
	l=tmp;
}

	list *l; int n; int x,i; l=NULL;
	printf("Add the number of elements to add\n");
	scanf("%d",&n);
	printf("Enter the elements\n");
	for(i=0;i<n;i++){
		scanf("%d",&x);
		l=addEl(l,x);
	}
	for(i=0;i<n;i++){
		printf("%d\n",l->val);
		l=l->next;
	}
	
	return 0;
}
Posted
Updated 20-Sep-16 2:46am
v3
Comments
[no name] 20-Sep-16 8:31am    
Just dumping your code into a forum posting is not asking a question.
Patrice T 20-Sep-16 8:31am    
"having trouble" is not informative.
state what is the problem and where.
Member 12749899 20-Sep-16 8:34am    
the program crashes when it begins the second for loop that prints the elements of the linked list
Patrice T 20-Sep-16 8:41am    
Use Improve question to update your question.
So that everyone can pay attention to this information.

The addEl function is supposed to return a list *, but you are not returning anything. And in that function, setting l=tmp; only sets the local parameter l, not the original pointer. You also need to move the structure definition, and the addEl function outside of main.
 
Share this answer
 
Comments
Member 12749899 20-Sep-16 8:48am    
I took the code from one of my schoolbooks and thought i could actually try so i can understand it better, and added the second for loop so i could see how it worked, so i think the problem is where i made changes...
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

This code:
list * addEl(list * l, int x){
	list * tmp;
	tmp=malloc(sizeof(list));
	tmp->val=x;
	tmp->next=1;
	l=tmp;
}

is plain wrong, tmp->next=1; you typed a '1' (one) instead of 'l' (lowercase L).
and you forgot to return something.
 
Share this answer
 
v3
Comments
Member 12749899 20-Sep-16 8:54am    
God, feeling so dumb right now, thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900