Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This is my code so far. It compiles fine and runs, however when i enter the number of the element i want to find, nothing happens.

What I have tried:

Here is the code I have tried:

int get_element(struct node **head, int index);


typedef struct node
	{
		int data;
		struct node* next;
	}node;

node* head = NULL;


int main(void)
{   
	int data_point;
	
	printf("what node would you like to find?\n");
	scanf("%d", &index);
	
	data_point = get_element(&head, index);
	
	printf("the value at node %d is %d", index, data_point);
	
	return (0);
}


int get_element(struct node **head, int index)
{
	node* current = *head;
	int count = 0;
	int data_point;
	
	while(current != NULL);
	{
		if(count == index)
		{
			data_point = current->data;
			
		}
		else
		{
			current = current->next;
			count++;
		}
	}
	return(data_point);
}
Posted
Updated 2-Oct-17 15:51pm
Comments
Peter_in_2780 2-Oct-17 20:31pm    
Did you create a list for your search to operate on? I don't see that.
[no name] 2-Oct-17 20:46pm    
Where is add_element()? BTW: The debugger should have told you the answer to your question.
PIEBALDconsult 2-Oct-17 21:19pm    
Perhaps you might want to break out of your while loop when you find the desired node?
«_Superman_» 3-Oct-17 1:51am    
You should update your question rather than repeating.

1 solution

Your code don't show the step where you store values in list.
The get_element function is buggy because data_point is not initialized if list have fewer elements than the one you search.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

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