Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incomplete array type?

When I compiled the following code with gcc -Wall -pedantic -ansi -std=c89, it compiled successfully without giving an error at the pointer assignment. Note that I convert from int (*)[4] to int (*)[].

int arr[4];
int (*p_arr)[] = &arr;

Assuming that there is some reason for allowing this (incompatible?) assignment, when I try to use it, the compiler gives incomplete type error error: invalid application of ‘sizeof’ to incomplete type ‘int[]’.

(void) sizeof(*p_arr);

This error makes me think what is the use of allowing the previous pointer assignment p_arr = &arr? Is this assignment allowed as per the standard?

I have used incomplete struct/union type (usually for forward declaration) and also come across the error incomplete array element type. But this incomplete array type is new to me. Is it possible in C standard and has a use case?

like image 577
user1969104 Avatar asked Nov 18 '15 10:11

user1969104


People also ask

Which is incomplete data type?

The void type is an incomplete type that cannot be completed. To complete an incomplete type, specify the missing information. The following examples show how to create and complete the incomplete types. To create an incomplete structure type, declare a structure type without specifying its members.

What does incomplete type mean in GDB?

It means that the type of that variable has been incompletely specified. For example: struct hatstand; struct hatstand *foo; GDB knows that foo is a pointer to a hatstand structure, but the members of that structure haven't been defined. Hence, "incomplete type".


1 Answers

This assignment didn't give any error because their types are compatible because arrays of unknown bound are compatible with any array of compatible element type. (For reference)-

int (*p_arr)[] = &arr;

But gives error on passing it as operand to sizeof operator because *p_arr is of incomplete type and you are not supposed to use incomplete types as operands to sizeof operator.

N1570 6.5.3.4

1 The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member[...].

Now what you can use it, here is a simple example -

#include <stdio.h>

int main(void){
    int arr[4]={1,2,3,4};
    int a[6]={1,2,3,3,1,1}; 
    int (*p_arr)[] = &arr;
    for(int i=0;i<4;i++)
       printf("%d",(*p_arr)[i]);
    printf("\n");
    p_arr=&a;
    for(int i=0;i<6;i++)
       printf("%d",(*p_arr)[i]);
    return 0;
}
like image 176
ameyCU Avatar answered Sep 21 '22 09:09

ameyCU