error: aggregate value used where an integer was expected

38,780

Solution 1

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.

You need to access the proper union member:

printf("%" PRIu64, mydata[0].val);

to select the uint64_t value. No need for the cast.

Also: Use PRIu64 to portably print 64-bit values, you can't assume that %llu is the right format specifier.

Solution 2

The "dirty" solution to access the first member of the nth element of the array of unions pointed to by mydata as an int64_t without knowing its name is:

#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.

Share:
38,780
Chinna
Author by

Chinna

Updated on July 05, 2022

Comments

  • Chinna
    Chinna almost 2 years

    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
    
  • Grijesh Chauhan
    Grijesh Chauhan over 10 years
    I think suggest OP PRIu64 also
  • unwind
    unwind over 10 years
    @GrijeshChauhan True, I edited that fix into the answer. Thanks.
  • radsdau
    radsdau over 8 years
    Vote for alerting me to the existence of PRIu64 etc :)