Click here to Skip to main content
15,878,970 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a program in C that does BFS to search for a goal vertex. The problem is that it spits out all the vertices it visited and not just the path to the goal. I can't quite come up with a solution for it without causing segmentation fault.

Suppose the input file is:

The first line is the number of vertices while the other lines list out the adjacency matrix.

Output comes out as 1--7--3--2--6--5--9--8--10 when searching for 10 when I just want to save the path 1--7--9--10. Can anyone recommend some new data structures so that I can change this path? What I have tried doesn't work.

Here is the code:

Any suggestion for data structures that i can use to save the path?

What I have tried:

I have tried implementing a queue but that just segfaults my program. I'm not sure where to go from here.
Updated 14-Sep-19 22:14pm

You should use the debugger to find your bugs. It often makes sense to write some output code in critical code pathes.

Use some IDE like Visual Studio and its outstanding debugging features.
Share this answer
I have tried implementing a queue but that just segfaults my program. I'm not sure where to go from here.

If you are getting a segmentation fault, it almost certainly means your pointers are "bad".
Which pointer? Dunno - we have no idea what code you wrote! :laugh:

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.

The debugger will let you stop your code while it is running so you can look at the content of variables and / or memory; run your code line by line to see what is happening (called "single stepping"); even change variables if you think they are wrong.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
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