1

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.

3
  • 1
    sizeof A doesn't do what you think it does. Google it. Commented Apr 26, 2015 at 16:38
  • 1
    You need sizeof A / sizeof *A to get number of elements of A. Commented Apr 26, 2015 at 16:39
  • You should not typedef bool yourself. Use stdbool instead (and use C99 or C11 standard). And why use a typedef for the struct when using struct-domain name lateron? Commented Apr 26, 2015 at 17:21

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Feel so stupid, especially since I went out and declared it from the beginning. :)
0
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.

1 Comment

Thank you. I have to use A for an assignment, I dislike it as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.