Iteratively assigning values to C Structures
I have a structured defined as
typedef struct{
char string1
char string2
int number1
char string3
}structure1
and want to assign the values to string1,string2,number1,string3 in a loop like this
structure1 bob
for(int i = 0,i<=4,i++)
{
bob.i = assigned value
}
now I understand that code above in it's generic form will only work for integers as you can't just go string = string for assignment, but the same problem arises as I don't know how to reference the values inside a struct without specifically naming them one by one. for strings there will be a second assignment relying on the i index to work out if it's a integer or string at the time so it can perform the assignment. I was thinking som开发者_运维知识库ething along the lines of enum's but I've never used them in a practical sense before, just theoretical.
It's not possible in C. The closest to that would be calculating field offsets and then using them to assign values:
int fieldOffset[4];
structure1 base;
fieldOffset[0] = (char*)&base.string1 - (char*)&base;
fieldOffset[1] = (char*)&base.string2 - (char*)&base;
fieldOffset[2] = (char*)&base.number1 - (char*)&base;
fieldOffset[3] = (char*)&base.string3 - (char*)&base;
structure1 structYouWantToAssign;
for (int i = 0; i < 4; ++i)
{
*((char*)&structYouWantToAssign + fieldOffset[i]) = assignedValue;
}
Warning: this code is just to demonstrate it is possible to assign fields without their name, but you should not use it!
Unfortunately that's not possible in C. It's be really cool, but nothing of the sort is in the syntax.
You could try a slightly different approach. Wanting to do that implies you're initialising them in which case you could do this:
#define STRUCT_DEF {"default", "another", 1234, "the last string" }
...
structure1 Variable = {"default", "another", 1234, "the last string"};
(that's assuming you meant char string1[STR_LEN] rather than just a single char.)
Alternatively you could try redefining your structure with arrays inside:
typedef struct{
char string[NUM_STRINGS][STR_LENGTH];
int number1;
}structure1
That way you can address the strings in a loop without naming each individually.
Use a function which assigns to the member:-
void BobAssign(struct* s, int i, void * value);
精彩评论