【C】Pointer (10) Incomplete Type: Structures / Unions
※ 日本語ページはこちら
Hi, this is Gocha.
As I explained, a structure or union type of unknown content s an incomplete type.
A structure or union type of unknown content (as described in 6.7.2.3) is an incomplete type. It is completed, for all declarations of that type, by declaring the same structure or union tag with its defining content later in the same scope.
ref: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#page=48
Let’s see 6.7.2.3.
6.7.2.3 Tags
Constraints
1. A specific type shall have its content defined at most once.
2. Where two declarations that use the same tag declare the same type, they shall both use the same choice of struct, union, or enum.
3. A type specifier of the form enum identifier without an enumerator list shall only appear after the type it specifies is complete.Semantics
ref: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#page=118
4. All declarations of structure, union, or enumerated types that have the same scope and use the same tag declare the same type. The type is incomplete111) until the closing brace of the list defining the content, and complete thereafter.
I think it is not easy to understand, so let’s see source codes.
At first, 1 A specific type shall have its content defined at most once.
gocha is defined twice , so error occurs, 6-7-2-3-1.c
#include <stdio.h>
#include <string.h>
int main (void ) {
struct people {
char name[20];
char gender[20];
int age;
} gocha;
struct people2 {
char name[20];
char gender[20];
int age;
} gocha;
printf("size of gocha is %ld\n",sizeof(gocha) );
strcpy(gocha.name, "gocha");
strcpy(gocha.gender, "male");
gocha.age = 37;
printf("name of gocha is %s\n",gocha.name );
printf("gender of gocha is %s\n",gocha.gender );
printf("age of gocha is %d\n",gocha.age );
return 0;
}
~
The result of compile of 6-7-2-3-1.c
$ gcc 6-7-2-3-1.c
6-7-2-3-1.c: In function ‘main’:
6-7-2-3-1.c:17:4: error: conflicting types for ‘gocha’
} gocha;
^
6-7-2-3-1.c:10:4: note: previous declaration of ‘gocha’ was here
} gocha;
^
gocha is defined only once, 6-7-2-3-2.c
#include <stdio.h>
#include <string.h>
int main (void ) {
struct people {
char name[20];
char gender[20];
int age;
} gocha;
/*
struct people2 {
char name[20];
char gender[20];
int age;
} gocha;
*/
printf("size of gocha is %ld\n",sizeof(gocha) );
strcpy(gocha.name, "gocha");
strcpy(gocha.gender, "male");
gocha.age = 37;
printf("name of gocha is %s\n",gocha.name );
printf("gender of gocha is %s\n",gocha.gender );
printf("age of gocha is %d\n",gocha.age );
return 0;
}
The result of compile and execution of 6-7-2-3-2.c
$ gcc 6-7-2-3-2.c
$ ./a.out
size of gocha is 44
name of gocha is gocha
gender of gocha is male
age of gocha is 37
That’s all for this time.