6

I'm looking to solve a math equation given as string to array of pointers like

char* equations = {"n+1", "n+2", "n*n+3"}

I want the compiler to consider strings inside the above character array as variables e.g "n" is a variable. So, when I assign this string to an 'int' so they will act like a mathematical operation like this:

int a = n+1;  

I was thinking the below method could work, but it is definitely not working because we can't assign a pointer's array to int. Even it did, but it's taking just the codes of it like A=65, but this is not my requirement:

a = equations[0];   //(compiler assume it like a = n+1)
2
  • 1
    X-Y problem indeed. Commented Dec 29, 2017 at 7:42
  • You knew it yourself. And why do you even need those kind of construct? Commented Dec 29, 2017 at 7:47

3 Answers 3

16

there are many ways to do this, for example you could parse each expression do some pattern matching and then create and expression from this, which is of course much easier said than done.

But I've found a library that I've not tested yet that do what you want(Or promise to do so), here is the link:

http://partow.net/programming/exprtk/index.html

Sign up to request clarification or add additional context in comments.

Comments

3

The compiler cannot do that for you, you will have to parse the strings into their components (variables, constants, operators) and then apply the appropriate operations yourself.

1 Comment

Quite a simple answer :)
1

No, what you want is not possible, because, in a compiled version of a C code, the notion of a "variable name" does not exist.

If you want to achieve this sort of things, you have to do this before you head into the compilation part, i.e, during the pre-processing part.

Otherwise, a more flexible way of achieving what you "probably" want is to make use of function pointers (as "callbacks", if you prefer). You can have different functions defined to do certain jobs and then, at run-time, you can choose any of the already defined functions to be called / invoked and collect the result in the desired variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.