Travv92
Travv92

Reputation: 801

C - Pointers, functions and recursion

Just trying to get some code to work involving pointers, functions and recursion:

Node * root = malloc(sizeof(Node));
root->data = "1";
root->next = NULL;
root->child = NULL;

Node * G = NULL;
BuildGraph(root, &G);
printf("Root is: %d\n", root->data);
Print(G, ">>"); // Custom Print function

And BuildGraph:

void BuildGraph(Node * head, Node ** G) {
    if (head->child == NULL) { // No child
        printf("Head has no child! %d\n", head->data);
        Push(head, &G);
        Print(G, ">>");
        return;
    }
    BuildGraph(head->child, &G);
    return;
}

And so when I run the program, my output goes like this:

Head has no child! 1 // printf in BuildGraph
G: 1>> // Print(G, ">>") in BuildGraph
Root is: 1
G is empty! // Print(G, ">>") in main

Anyone know the reason G is not carrying over into main?

Thanks.

Upvotes: 0

Views: 889

Answers (1)

chux
chux

Reputation: 154322

Within void BuildGraph(), BuildGraph(head->child, &G); should be BuildGraph(head->child, G);. No &, Likely the same with Push(head, &G);

Within your build function, G is a Node **. Outside in main(), G is a Node *.

Consider using a different and more expansive variable name than G within BuildGraph(). Maybe something like

void BuildGraph(Node * head, Node ** AddressG) {
    if (head->child == NULL) { // No child
        printf("Head has no child! %d\n", head->data);
        Push(head, AddressG);
        Print(AddressG, ">>");
        return;
    }
    BuildGraph(head->child, AddressG);
    return;
}

I am confident that you compilation provided warning messages concerning this issue. If they did not recommend investigating how to turn them on.

Upvotes: 2

Related Questions