K.KM
K.KM

Reputation: 1

String to Struct variables in C , without pointer,define

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?

Upvotes: 0

Views: 59

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126175

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!
}

Upvotes: 1

Related Questions