Arrow operator (->) usage in C

后端 未结 12 2074
醉梦人生
醉梦人生 2020-11-22 04:41

I am reading a book called \"Teach Yourself C in 21 Days\" (I have already learned Java and C# so I am moving at a much faster pace). I was reading the chapter on pointers a

12条回答
  •  再見小時候
    2020-11-22 05:19

    I had to make a small change to Jack's program to get it to run. After declaring the struct pointer pvar, point it to the address of var. I found this solution on page 242 of Stephen Kochan's Programming in C.

    #include 
    
    int main()
    {
      struct foo
      {
        int x;
        float y;
      };
    
      struct foo var;
      struct foo* pvar;
      pvar = &var;
    
      var.x = 5;
      (&var)->y = 14.3;
      printf("%i - %.02f\n", var.x, (&var)->y);
      pvar->x = 6;
      pvar->y = 22.4;
      printf("%i - %.02f\n", pvar->x, pvar->y);
      return 0;
    }
    

    Run this in vim with the following command:

    :!gcc -o var var.c && ./var
    

    Will output:

    5 - 14.30
    6 - 22.40
    

提交回复
热议问题