Reputation: 29
I am new to C, know some Java. Trying to write a program that accepts 2D array that represents a directed adjacency matrix, and two numbers, scans the array and returns true if there is a directed path between them (top-down).
I am running into a problem with C implementation. Apparently I have to use pointers to values in array, whilst in Java I could've use values from array (compare, return to function, etc).
I'm pretty sure the logic is in place, I just need help with allocating '*'s in the right places and amounts.
Here's the code:
#include <stdio.h>
#define N 12
typedef int bool;
enum {false, true};
typedef struct adj_mat{
int A [N][N];
}adj_mat;
int path(struct adj_mat A, int origin, int dest){
int i;
if (origin == dest) return true;
for (i = 0; i < sizeof(A);i++){
if (A[origin][i]){
return path (A, i, dest);
}
}
return false;
}
Thanks in advance.
Upvotes: 1
Views: 72
Reputation: 5587
sizeof(A)
This probably does not give you what you expect. It is the number of bytes, not the number of elements.
A[origin][i]
Here you are trying to index the struct adjmat
which doesn't work. You probably wanted to index the member A
. Try:
A.A[origin][i]
It would probably be a good idea to rename adj_mat A
to something else to avoid confusion.
You should also pass the address of A
to the function and use adj_mat*
as the argument type. If I understand correctly you want the recursion to operate on the same object.
Upvotes: 0
Reputation: 23058
for (i = 0; i < sizeof(A);i++){
This should be for (i = 0; i < N; i++){
.
Also, your algorithm may not terminate since it didn't take care of cycles in graph.
Upvotes: 2