Incomplete array type?

前端 未结 1 1586
闹比i
闹比i 2020-12-18 23:37

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 tha

相关标签:
1条回答
  • 2020-12-19 00:29

    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;
    }
    
    0 讨论(0)
提交回复
热议问题