Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
");
    p_arr=&a;
    for(int i=0;i<6;i++)
       printf("%d",(*p_arr)[i]);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...