[Fixed] error: aggregate value used where an integer was expected – C

Photo of author
Written By M Ibrahim
abstract-class alpinelinux format-specifiers printf unions

Quick Fix: Change mydata[0] to mydata[0].val to access the uint64_t value. Also, use PRIu64 to portably print 64-bit values, as %llu may not be the correct format specifier on all platforms.

The Problem:

You have a union with multiple members, and you are trying to access one of the members as if it were an integer. This is not allowed because a union can only hold one value at a time, and the compiler does not know which member you want to access.

The Solutions:

Solution

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 directly cast to uint. You need to access the proper union member:

printf("%llu\n", (uint)_data[0].val);

to select the uint value. No need for the cast actually.

Also, use PRIu64 to portably print 64-bit values; you can’t assume that %llu is the right format specifier.

Solution 2:

The error is because the function expects an integer argument, but instead, it is passing an array of structures. The correct way to access the first member of the structure is to cast the pointer to the array to a pointer to the structure, and then access the first member of the structure using the pointer.

Here’s the corrected code:

#include <stdio.h>

union data 
{
    uint64_t val;
    ...
};

func(union data mydata[])
{ 
    size_t n = 3;
    printf("%"PRIu64, *((uint64_t *)(mydata + n)));     
}