Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

Create a tree using struct and for loops in C

I have a question. I'm trying to create a tree. The full code is large so it is difficult for me to enter here. So a summary of it is given below.

struct sample *fn_02(void);
struct sample *fn_03(void);

// Main Function
int main(void) {
    struct sample *tree;

    tree = fn_01();
}

// First Function
struct sample *fn_01(void) {
    for(;;) {
        switch(..) {
            case 1:
                return fn_02();

            case 2:
                return fn_03();
        }
    }
}

// Second Function
struct sample *fn_02(void) {
    struct sample *node;

    return node;
}

// Third Function
struct sample *fn_03(void) {
    struct sample *node;

    return node;
}

I want to create a tree. So I create a structure called struct sample {}; and create a 3 functions for it.

There is an infinity loop in the first ( fn_01() ) function and The values returned by fn_02 and fn_03 should create a tree.

This is the problem I have:

  • The loop in fn_01 should continue to work.
  • But when fn_02 and fn_03 are returned the loop ( and function ) stops.
  • But a return is essential to creating the tree. And the for loop must continue to work.

Can you suggest another solution to do this please?

question from:https://stackoverflow.com/questions/65951458/create-a-tree-using-struct-and-for-loops-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's difficult to answer without seeing more codes, but you probably may handle that by postponing the return statement :

struct sample *fn_01(void) {
    sample * s = NULL;
    for(;;) {
        switch(..) {
            case 1:
                s = fn_02();
                break;
            case 2:
                s = fn_03();
                break;
        }
        // Check s and/or do something with it. Return only when relevant
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...