简体   繁体   中英

Binary Tree Struct containing Multiple Arrays

Just as a disclaimer, I am not looking for any hard code solutions, but merely a nudge in the right direction.

Essentially, I need to create a tree, that contains two arrays of data in each Node and two separate arrays of chars.

struct Node {
    char *name;
    char *number;
    struct Node *left;
    struct Node *left;
};

That's my struct at the moment, and the input is in the form:

name number
name number
name number
.

The . being the termination, now, I have a theory for how to parse that, ie getchar until . and scanf the name and number into an array. But from this point, I'm unsure how exactly I need to pass those arrays to a function to add the stuff to the tree, where I define the size of the array, etc. Can someone give some tips for this problem?

First of all, you need to use dynamic memory. The size of your arrays will be defined at runtime, after you have read them, from a file I guess.

If the char* you read are null-terminated (ie the last character is '\\0'), you can use the strlen function to get their size, and pass that value to malloc in order to allocate the memory before you use strcpy to copy the string into that memory. Don't forget to call free to return everything you malloc 'ed

So just pass two char* to the function which will insert them in your data structure (is it a binary tree or a try? You used one term in the title and another in your question)

searched google for "c binary tree tutorial":
http://www.cprogramming.com/tutorial/c/lesson18.html

I would do a stack type:

typedef struct
{
int pos;
char *array;
int size;
} charArray;

charArray *newCharArray();

void pushCharArray(charArray * ca, char c);
void popCharArray(charArray *ca);


charStack *name;
charStack *number;

Inside pushCharArray you should check if ca is null or not, increment size if you need more space, increment the position...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM