简体   繁体   中英

Accessing certain elements in an Struct in C

So I have the following struct I created:

struct _I_TypeInstructions {
    const char *instructionName;
    char *opcode;
} I_TypeInstructions[] = { { "lw", "100011" }, { "sw", "101011" }, { "beq",
        "000100" } };
typedef struct _I_TypeInstructions I_TypeInstructionsStruct;

If I have a new instructionName and I want to check if it is in the I_TypeInstructionsStruct how do I iterate through just the *instructionName part of the struct above. For example the function I want to write would look something like

bool checkIfInstructionIsI_Type(char *instructionName) {
    // somehow iterate through instructionNames in the struct above
    // checking if parameter char *instructionName in this method is equal to 
    // "lw" "sw" "beq" but skipping over the binary numbers.
}

Searching a list of structs is rather straight forward:

bool checkIfInstructionIsI_Type(char *instructionName) 
{
    for (int i = 0; i<NumInstructions; i++)
    {
        if (strcmp(I_TypeInstructions[i].instructionName, instructionName) == 0)
        {
            return true;
        }
    }
    return false;
}
int i;
for(i = 0; i < 3; ++i)
{
    if (strcmp(instructions[i].instructionName, instructionName) == 0)
    {
        printf("Match found");
    }
}

It's generally more useful to return the actual element that matches your string. It's the same amount of work anyway.

Add an empty element to the end of your array and then you have a end marker.

typedef struct _I_TypeInstructions {
    const char *instructionName;
    char *opcode;
} I_TypeInstructionsStruct;

I_TypeInstructionsStruct I_TypeInstructions[] = {
{ "lw",  "100011" },
{ "sw",  "101011" },
{ "beq", "000100" },
{ 0,     0}
};

I_TypeInstructionsStruct *find_instruction(char *name)
{
    I_TypeInstructionsStruct *i ;
    for (i = I_TypeInstructions ; i->instructionName ; i++)
        if (!strcmp(i->instructionName,name)) return i ;
    return 0 ;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM