PnP
PnP

Reputation: 3185

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, i.e. 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?

Upvotes: 2

Views: 311

Answers (3)

dario_ramos
dario_ramos

Reputation: 7309

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 (i.e. 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)

Upvotes: 1

pamojarpan
pamojarpan

Reputation: 63

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

Upvotes: 0

yurib
yurib

Reputation: 8147

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

Upvotes: 0

Related Questions