Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flex, getting data out of yytext #62

Open
m8pple opened this issue Jan 24, 2018 · 1 comment
Open

Flex, getting data out of yytext #62

m8pple opened this issue Jan 24, 2018 · 1 comment

Comments

@m8pple
Copy link
Contributor

m8pple commented Jan 24, 2018

From someone who couldn't attend lab:

I have yet to successfully extract the data in yytext. I understand that it
is a global variable that exists in the flex produced C++ code, but I have
not yet been able to use it correctly. So far, I have been trying to implement
it by using it in the main, but this has failed to work. Is it possible to gain
some guidance?

@m8pple
Copy link
Contributor Author

m8pple commented Jan 24, 2018

This was a fairly common problem in the lab, and a lot
of it comes down to problems of pointers-to-values versus
values, and lifetime of objects.

yytext should be seen as something that exists only within
the flex file - from an encapsulation/isolation point of view
it is better to only use it within the flex source file.

So the point of communication between the two is the yylval
variable, which is there to act as a very constrained
mechanism for passing information from the flex file to
the c++ file with the main.

So we have:

  • yytext : a c-style string (char *) containing the current
    matching characters
  • yyval.wordValue : a pointer to a c++ string (std::string *)
    which should contain a string which is allocated on the
    flex side, then used and deallocated on the histogram_main
    side.

Operations we could use are:

  • yylval.wordValue = std::string;
    Allocate a new string object.

  • *yylval.wordValue = yytext;
    (Notice the *, which turns the pointer to std::string into a
    reference to std::string).
    Assigns the string pointed to by yytext to the std::string currently
    pointed to by yylval.wordValue.

  • std::string s = *yylval.wordValue;
    Create a copy of the std::string currently pointed to by
    yylval.wordValue

  • delete yylval.wordValue;
    Free the std::string pointer to by yylval.wordValue.

The first two are important on the lexing side, as you want
to allocate a std::string, then choose the contents of that
string.

The second two are important on the main side, as you want
to get the value out of the std::string, then release it.

Hopefully that helps a bit, as I think that the new and
dereferencing were the biggest problems people encountered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant