Linux 错误:在需要整数的地方使用了聚合值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20994959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: aggregate value used where an integer was expected
提问by Chinna
I am having following union
我有以下工会
union data {
uint64_t val;
struct{
....
}
};
and I have a function
我有一个功能
func(union data mydata[])
{
printf("%llu",(uint64_t)mydata[0]); // Here is the error
}
When i compile this code it is giving following error
当我编译这段代码时,它给出了以下错误
error: aggregate value used where an integer was expected
采纳答案by unwind
You are failing to access a field of the indexed union array: mydata[0]is a value of type union data, and can't be cast to uint64_t.
您无法访问索引联合数组的字段:mydata[0]是 type 的值union data,并且不能强制转换为uint64_t。
You need to access the proper union member:
您需要访问适当的工会成员:
printf("%" PRIu64, mydata[0].val);
to select the uint64_tvalue. No need for the cast.
来选择uint64_t值。不需要演员表。
Also: Use PRIu64to portably print 64-bit values, you can't assume that %lluis the right format specifier.
另外:PRIu64用于可移植地打印 64 位值,您不能假设这%llu是正确的格式说明符。
回答by alk
The "dirty" solution to access the first member of the nthelement of the array of unions pointed to by mydataas an int64_twithoutknowing its name is:
在不知道其名称 的情况下访问as an指向的联合数组的n第 th 个元素的第一个成员的“脏”解决方案是:mydataint64_t
#include <inttypes.h>
#include <stdio.h>
union data
{
uint64_t val;
...
};
func(union data mydata[])
{
size_t n = 3;
printf("%"PRIu64, *((uint64_t *)(mydata + n));
}
This works as the first member's address of a union or struct is guaranteed to be the same as the address of the union or struct itself.
这是因为联合或结构的第一个成员地址保证与联合或结构本身的地址相同。

