struct z_st {int a ; char B}; typedef struct z_st Zarr_k[10]; Zarr aZ; struct z_st bZ[10]; aZ和bZ被认为是不同的类型,为什么?

pokxtpni  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(42)

我试图传递指向结构数组的指针,但数组是以两种不同的方式定义的,我很难弄清楚在每种情况下使用哪种语法以及为什么。
当我尝试用GCC编译它时,我得到了以下错误消息。我本以为aZ和bZ本质上是一样的,它们的语法本质上也是一样的,但事实并非如此。我应该如何看待这个问题?
我尝试了不同的方法来定义指向两个“等价”变量的指针,并将这些指针传递给函数。我发现了一种有效的方法,但我不知道为什么。

struct z_st {int i ; char c  ; } ;
typedef struct z_st Zarr_k[10] ;

int foo( Zarr_k *pz ) { 
    return (*pz)[0].i++ ;   // pz->[0].i gives an error 
}
int bar ( struct z_st barz[10] ) { 
    return barz[0].i ;  
}
int main (int argc, char *argv[] ) {
   int ra,rb ; 
    struct z_st aZ[10];  // aZ is a 10-array of structs type z_st
    Zarr_k      bZ    ;     // bZ is a
    struct z_st *paz = &aZ[0] ;     // &az    does not work; incompatible pointer type  
    Zarr_k      *pbz = &bZ ;        // &bZ[0] does not work; incompatible pointer type
    ra = foo(paz) ;                     // gives compile error/warning.
    rb = foo(pbz) ;                     // Ok
    ra = bar(paz) ;                     // OK
    rb = bar(pbz) ;                 // error 
    return 0 ; 
}

字符串
编译器警告和错误是:

> struct_type_clash.c:16:18: warning: passing argument 1 of ‘foo’ from incompatible pointer type [-Wincompatible-pointer-types]
> 16 |         ra = foo(paz) ;  // gives compile error/warning.
>       |                  ^~~
>       |                  |
> struct z_st *
> struct_type_clash.c:4:18: note: expected ‘struct z_st (*)[10]’ but argument is of type ‘struct z_st *’
> 4 | int foo( Zarr_k *pz ) {
>       |          ~~~~~~~~^~
> struct_type_clash.c:19:18: warning: passing argument 1 of ‘bar’ from incompatible pointer type [-Wincompatible-pointer-types]
> 19 |         rb = bar(pbz) ; // error
>       |                  ^~~
>      |
      |                  struct z_st (*)[10]
> struct_type_clash.c:7:23: note: expected ‘struct z_st *’ but argument is of type ‘struct z_st (*)[10]’
> 7 | int bar ( struct z_st barz[10] ) {

sczxawaw

sczxawaw1#

你写了*

在C语言中,Zarr_k *pz声明了一个指向10个结构体的数组的指针,相当于struct z_st (*pz)[10]。相比之下,struct z_st barz[10] * 作为函数参数 * 声明了一个直接指向结构体的指针,而不是数组;这是因为用数组类型声明的参数被“重写”为指向该数组的元素类型的指针,数组对象几乎总是被转换为指向其第一个元素的指针,通常称为“decay”。
错误消息告诉您这一点,尽管您错误地将其作为引用文本而不是代码发布,导致一些提示消失。
int foo( Zarr_k pz )给出了与当前bar相同的类型,即struct z_st *
int bar ( struct z_st (*barz)[10] )提供与当前foo相同的类型

相关问题