Home > Back-end >  Dynamically Access Variable Inside a Struct C
Dynamically Access Variable Inside a Struct C

Time:09-23

I'm new to C and very confused on how to approach this. In Javascript, I can do something like this to access an object dynamically very easily:

function someItem(prop) {
    const item = {
        prop1: 'hey',
        prop2: 'hello'
    };
    return item[prop];
}

In C , I'm assuming I have to use a Struct, but after that I'm stuck on how to access the struct member variables dynamically.

void SomeItem(Property Prop)
{
    struct Item
    {
        Proper Prop1;
        Proper Prop2;
    };
    // Item[Prop] ??
 }
       

This could be terrible code but I'm very confused on how to approach this.

CodePudding user response:

As mentioned in a comment, in C you would not define a custom structure for this, but rather use a std::unordered_map. I don't know Javascript, though if Property is an enum (it could be something else with small modifications) and return item[prop]; is supposed to return a string, then this might be close:

#include <string>
#include <unordered_map>
#include <iostream>

enum class Property { prop1,prop2};

std::string someItem(Property p){
    const std::unordered_map<Property,std::string> item{
        {Property::prop1,"hey"},
        {Property::prop2,"hello"}
    };
    auto it = item.find(p);
    if (it == item.end()) throw "unknown prop";
    return it->second;
}

int main(){
    std::cout << someItem(Property::prop1);
}

std::unordered_map does have a operator[] that you could use like so return item[p];, but it inserts an element into the map when none is found for the given key. This is not always desirable, and not possible when the map is const.

CodePudding user response:

This is a simple example of how to create an instance of a struct and then access its members:

#include <iostream>
#include <string>

struct Item {
    std::string prop1 = "hey";
    std::string prop2 = "hello";
};

int main() {
    Item myItem;
    std::cout << myItem.prop1 << std::endl; // This prints "hey"
    std::cout << myItem.prop2 << std::endl; // This prints "hello"
    return 0;
}

As mentioned in the comments, it looks like you might want a map. A map has keys and values associated with them, as an example you could have a key "prop1" be associated with a value "hey":

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, std::string> myMap;
    myMap["prop1"] = "hey";
    myMap["prop2"] = "hello";
    std::cout << myMap["prop1"] << std::endl; // This print "hey"
    std::cout << myMap["prop2"] << std::endl; // This print "hello"
    return 0;
}

The first would be considered "normal" struct usage in C and the other is more applicable to cases where you have to look things up by keys

  • Related