迭代地为 C 结构赋值
我有一个定义为的结构
typedef struct{
char string1
char string2
int number1
char string3
}structure1
,想要在这样的循环中将值分配给 string1,string2,number1,string3
structure1 bob
for(int i = 0,i<=4,i++)
{
bob.i = assigned value
}
现在我明白上面的通用形式的代码仅适用于整数,因为你不能只使用 string = string进行分配,但出现了同样的问题,因为我不知道如何引用结构内的值而不具体一一命名它们。对于字符串,将有第二个赋值,依赖于 i 索引来确定它当时是整数还是字符串,以便它可以执行赋值。我正在思考一些类似于枚举的东西,但我以前从未在实际意义上使用过它们,只是理论上的。
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 something along the lines of enum's but I've never used them in a practical sense before, just theoretical.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C 中这是不可能的。最接近的方法是计算字段偏移量,然后使用它们来分配值:
警告:此代码只是为了演示可以在没有名称的情况下分配字段,但是您不应该不使用它!
It's not possible in C. The closest to that would be calculating field offsets and then using them to assign values:
Warning: this code is just to demonstrate it is possible to assign fields without their name, but you should not use it!
不幸的是,这在 C 中是不可能的。这确实很酷,但语法中没有这样的内容。
Unfortunately that's not possible in C. It's be really cool, but nothing of the sort is in the syntax.
您可以尝试稍微不同的方法。想要这样做意味着您正在初始化它们,在这种情况下您可以这样做:(
假设您的意思是 char string1[STR_LEN] 而不仅仅是单个字符。)
或者您可以尝试使用内部数组重新定义结构:
这样您可以在循环中寻址字符串,而无需单独命名每个字符串。
You could try a slightly different approach. Wanting to do that implies you're initialising them in which case you could do this:
(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:
That way you can address the strings in a loop without naming each individually.
使用分配给成员的函数:-
Use a function which assigns to the member:-