【C】Pointer (9) Incomplete Type: Arrays with Unknown Number of Elements or Sizes

※ 日本語ページはこちら

I will explain about an array type of unknown number of elements / unknown size is an incomplete type.

22.
An array type of unknown size is an incomplete type. It is completed, for an identifier of that type, by specifying the size in a later declaration (with internal or external linkage).

ref: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#page=48

If we apply the definition of incomplete type to 1., we will have below sentence.

As I explained in below, incomplete Type is the type which cannot determine size of object.

An array type of unknown size is incomplete type because size of object cannot be determined.

Too obvious, so I complement as below.

An array type of unknown number of elements/sizes is incomplete type because size of object cannot be determined.

For (20), only thing we should understand so far is we have some cases that we define size later by using internal linkage or external linkage.
For details about internal linkage or external linkage, please refer page 42.

Just in case you are interested in, I uploaded some codes and results of compiling and executing.

Using sizeof to incomplete type. Getting expected error. 1.c

#include <stdio.h>
int a[];
int main ( void ) {

	printf("size of a is %d\n",sizeof(a));

	int a[3];

	a[0] = 0;
	a[1] = 1;
	a[2] = 2;


	printf("a[0] is %d\n",a[0]);
	printf("a[1] is %d\n",a[1]);
	printf("a[2] is %d\n",a[2]);

	printf("size of a is %d\n",sizeof(a));
	return 1;

}

The result of compilation of 1.c

$ gcc 1.c 
1.c: In function ‘main’:
1.c:5:35: error: invalid application of ‘sizeof’ to incomplete type ‘int[]’
  printf("size of a is %d\n",sizeof(a));
                                   ^
1.c:18:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
  printf("size of a is %d\n",sizeof(a));
  ^
1.c: At top level:
1.c:2:5: warning: array ‘a’ assumed to have one element [enabled by default]
 int a[];
     ^

Using sizeof after the number of elements of array is defined. 2.c

#include <stdio.h>
int a[];
int main ( void ) {

//printf("size of a is %d\n",sizeof(a));  

	int a[3];

	a[0] = 0;
	a[1] = 1;
	a[2] = 2;


	printf("a[0] is %d\n",a[0]);
	printf("a[1] is %d\n",a[1]);
	printf("a[2] is %d\n",a[2]);

	printf("size of a is %d\n",sizeof(a));
	return 1;

}

The result of compilation and execution of 2.c.

$ gcc 2.c
2.c: In function ‘main’:
2.c:18:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
  printf("size of a is %d\n",sizeof(a));
  ^
2.c: At top level:
2.c:2:5: warning: array ‘a’ assumed to have one element [enabled by default]
 int a[];
     ^
demo@ubuntu:~/SelfStudy/c/pointers/ImcompleteType$ ./a.out 
a[0] is 0
a[1] is 1
a[2] is 2
size of a is 12

That’s all for this time.