Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incompatible struct types in casts/assignment?

Tags:

c

struct

This is a follow-up to this question.

I'm trying to avoid using an explicit typedef to copy one array to another through casts like this:

#include <stdio.h>

int main(void)
{
  int i;
  int dst[] = { 10, 20, 30 }, src[] = { 1, 2, 3 };

  *(struct{int _[3];}*)dst = *(struct{int _[3];}*)src;

  for (i = 0; i < 3; i++) printf("%d\n", dst[i]);
  return 0;
}

With gcc I'm getting arrcpy.c:8: error: incompatible types in assignment, however with Open Watcom it compiles fine (and works as I expect it, printing 1 through 3).

Is the gcc's behavior per the standard or not? If it is, what's the relevant chapter and section? I can't understand why two identical type definitions struct{int _[3];} aren't the same (or compatible) in the gcc's eyes.

EDIT: I know full well it's a bad coding style. The question is about a different thing. I'm curious if there's a logical rationale behind the gcc's behavior, if it's legit.

like image 531
Alexey Frunze Avatar asked Oct 25 '11 00:10

Alexey Frunze


1 Answers

The gcc behavior is right, the types are two unrelated unnamed structures. Each of those structs, while having the same memory layout, have different names. If you really want to do that, then use a typedef.

like image 130
K-ballo Avatar answered Oct 19 '22 22:10

K-ballo