2016-03-31 11 views
-4
struct circle { 
int center; 
int radius; 
}; 
struct circle *cir; 

cir.center 
cir->radius 
(cir.radius) 
(cir->center)  

この最後の4行の違いは何ですか?私は、cir.centerが変数cirによって指し示されている構造体サークルのメンバーにアクセスしていることを知っています。 cir-> radiusは同じですが、ポインタ変数cirによって指されます。しかし、()は何をしますか?cir.radiusと(cir.radius)の差

+1

括弧は単独では何もしません。彼らはより大きな表現で使用されるときに違いを生むかもしれません。完全な声明を提出してください。 – user694733

+2

違いは、 'cir'はポインタなので' cir.center'はコンパイルされないということです。 –

+3

'(* cir).radius'は' cir-> radius'と同じです –

答えて

3

であるあなたが->演算子を使用する必要がstruct circle *cir;すなわち構造体へのポインタとして宣言しています構造体の要素にアクセスする

cirだけstruct circle cir;すなわち型構造の変数として宣言されている場合、あなたは()ような構造の要素にアクセスに

.演算子を使用する必要がありますので、ここで任意の違いはありません。 (cir.radius) = cir.radius

+0

これは私が探していたものです。ありがとうございます。 – JBladevr

+0

これはあなたの質問の答えである場合は、答えの近くのチックをクリックしてそれを受け入れることができます:) – Nutan

1

cir.center - 構造体の内部へのアクセスcentercirポインタ
cir->radiusなかった場合 - cir逆参照し、次にradius
(cir.radius)アクセス - cir.centercir場合は
(cir->center)ポインタなかったと同じ - cirとアクセスcenter間接参照

ポインタなしの違いに注意してください。

struct circle { 
    int center; 
    int radius; 
}; 
... 
circle cir; 
cir.center = 5; 
printf("%d", cir.center); 
//   ^

とポインタ

circle* cir; 
... 
cir->radius = 5; 
// ^^ 

cir->radiusを書くのもう一つの方法は、cirとして(*cir).radius

0

(cir->center)=cir->centerは、以下のものを参照してください。

#include<stdio.h> 

struct circle 
{ 
    int r; 
}; 

int main(void) 
{ 
    struct circle obj; 
    struct circle* obj1=&obj; 

    printf("Enter radius : "); 
    scanf("%d",&obj.r); 
    /* here membership operator '.' has precedence over '&' 
    * consider obj.r as a variable x, then normal scanf procdedure 
    * applies that is you're accessing the memory using &x 
    */ 
    printf("Entered radius : %d\n",obj.r); 
    /* For printf we don't need the '&' */ 

    printf("Enter radius : "); 
    scanf("%d",&(*obj1).r); 
    /* Now things have become really dirty 
    * First we need to use the dereference operator on obj1 which is a 
    * pointer to structure and then 
    * user the membership operator '.' to access the variable 
    * The reference operator '& above here has the least preference 
    * it gives the address of the chunk of memory dedicated to 'r' 
    */ 

    printf("Entered radius : %d\n",(*obj1).r); 


    printf("Enter radius : "); 
    scanf("%d",&obj1->r); 

    /* Well, here the 'obj1->' replaces the '(*obj1).' and 
    * both have the same meaning. 
    * The -> is called the indirection operator which makes things 
    * look neater. Note that you still need the reference operator 
    * '&' for the structure member 'r' 
    */ 

    printf("Entered radius : %d\n",obj1->r); 
    return 0; 
} 

上記は有効なものであり、実際にコードで物事をより明確にするために括弧を使用することができます。