0

I want a way to convert a string to struct variable.

ex)

struct DAT
{
    int a,b;
    char c,d;
    float e,f;
}DAT1,DAT2,Main_data;

main()
{
    Test_function(1)
}

Test_function(int num)
{
    Main_data = DAT(num)   // If num is 1, Main_data = DAT1
}

I want this program. But I can't use define and pointer. This mean I don't use * and # operators.

How do I do this?

7
  • 3
    Ca you be straightforward and clear with example what you really want to achieve Commented Feb 20, 2017 at 3:47
  • struct DAT dat_array[2]; Main_data = dat_array[num-1]; Commented Feb 20, 2017 at 3:47
  • if ( num == 1 ) Main_data = DAT1; else Main_Data = DAT2; Commented Feb 20, 2017 at 3:53
  • Note that modern C (meaning 'C written since about 1990') should have an explicit return type for every function — int main(void), void Test_function(int num), etc. Yes, compilers do still allow the sloppy old notation — but that doesn't make it good style and C99 and C11 explicitly disallow 'implicit int return type'. Commented Feb 20, 2017 at 4:15
  • The struct type variable can add more. but I do not know that how does it rise more. How can I do this?... And, type error is my miss. Sorry. Commented Feb 20, 2017 at 4:36

1 Answer 1

1

You can't 'compute' with variable names at runtime -- the names in your program really only exist at compile time and once your program is compiled, they're not available. So you need to test the value and enumerate all the possibilities in your program if you want it to decide between different variables at runtime. Something like:

void Test_function(int num)
{
    switch(num) {
    case 1:
        Main_data = DAT1;
        break;
    case 2:
        Main_data = DAT2;
        break;
    default:
        fprintf(stderr, "Invalid num %d for DAT\n", num);
    }
}

While this works, its verbose and error prone, which is why arrays and pointers exist -- they make it much easier:

struct DAT DAT[3], Main_data;

void Test_function(int num)
{
    Main_data = DAT[num];  // Undefined behavior if num is out of range!
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! But The struct type variable can add more. but I do not know that how does it rise more. With this condition, How do I do this?...

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.