Hi guys, I'm working on a school project right now for theory of language. I'm a C newbie and I encountered a problem that I can't seem to solve.
Any way, let me give you some background on the project. I'm suppose to implement a language generator from a given set of grammar.
I have my lexical analyzer working that spits out tokens. The next step is, I'm constructing the grammar as a form of link-list/arrays.
Here are my data structures
Code:
struct token{
// Terminal or Non-Terminal
int type;
// If it is a non terminal, then it is the name, else, it is the content
char *content_ptr;
// The node is non-terminal, node_ptr points to an array of nodes below the current node.
struct token_array *aptr;
};
struct token_array{
int num_of_elements;
struct token *tptr;
};
If the data strucutre is built correctly, it should look something like this
token_array ->an array of tokens
each token then points to NULL if it is a terminal or another token_array that points to more tokens in an array (non terminals).
And here is the code in trouble,
Code:
struct token_array build(FILE *file){
int first_token=TRUE;
char *char_ptr;
struct token token_ptr;
struct token_array grammar = {0, NULL};
struct token_array temp_token_array = {0, NULL};
do{
char_ptr = next_token(file);
if(char_ptr!=NULL){
token_ptr = *token_wrapper(char_ptr);
if(char_ptr[0]=='\n'){
first_token=TRUE;
grammar.tptr[grammar.num_of_elements-1].aptr = &temp_token_array;
temp_token_array.num_of_elements=0;
temp_token_array.tptr=NULL;
}
else{
if(first_token==TRUE){
first_token=FALSE;
grammar.num_of_elements++;
grammar.tptr=realloc(grammar.tptr, grammar.num_of_elements*sizeof(struct token));
grammar.tptr[grammar.num_of_elements-1]=token_ptr;
}
else{
temp_token_array.num_of_elements++;
temp_token_array.tptr=realloc(temp_token_array.tptr, temp_token_array.num_of_elements*sizeof(struct token));
temp_token_array.tptr[temp_token_array.num_of_elements-1]=token_ptr;
}
}
printf("%s\n", char_ptr);
}
}while(char_ptr!=NULL);
print_grammar(grammar);
return grammar;
}
the main function look somethins like this....
Code:
grammar = build(file);
printf("-------Grammar--------");
print_grammar(grammar);
The main problem is, when use printf, it destroyes the data structure. I get random values. If I do printf within the build function then everything is fine.
I think it have to do with the scope of the variable....
But I really is cruless
Thanks in advance for any help you can provide!