0

gcc is able to compile with no problems if I try to assign the address of global integer array into a field a global struct as you can see in the snippet below

#include <stdio.h>
#include <stdint.h>

int integer_array[4] = {0, 1, 2, 3};

struct my_struct {
        uintptr_t addr;
};

struct my_struct s = {
        .addr = (uintptr_t)t
};


int main() {
        printf("0x%lx\n", s.addr);
}

However, If I modify the above code and instead of an array I pass a structure, gcc is throwing the following error.

#include <stdio.h>
#include <stdint.h>

struct test {
        int integer_array[4];
};
struct test t;

struct my_struct {
        uintptr_t addr;
};

struct my_struct s = {
        .addr = (uintptr_t)t
};


int main() {
        printf("0x%lx\n", s.addr);
}
test.c:15:1: error: aggregate value used where an integer was expected
   15 | };

Can anybody explain to me why this is happening ?

  • In `(uintptr_t)t`, the name of an array implicitly converts to a pointer to the first element. That's not the case for a struct, you'd need `&t`. Also, your first code block uses `t`, an identifier only your 2nd code block defines. – Peter Cordes Dec 14 '22 at 15:48
  • @PeterCordes it is because structs can be assigned - thus no decay – 0___________ Dec 14 '22 at 16:30

0 Answers0