pointer to array c++

后端 未结 3 1664
鱼传尺愫
鱼传尺愫 2020-11-28 06:52

What is the following code doing?

int g[] = {9,8};
int (*j) = g;

From my understanding its creating a pointer to an array of 2 ints. But th

3条回答
  •  广开言路
    2020-11-28 07:33

    The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int

      int g[] = {9,8};
      int (*j) = g;
    

    could also be rewritten as

      int g[] = {9,8};
      int *j = g;
    

    which could also be rewritten as

      int g[] = {9,8};
      int *j = &g[0];
    

    a pointer-to-an-array would look like

      int g[] = {9,8};
      int (*j)[2] = &g;
    
      //Dereference 'j' and access array element zero
      int n = (*j)[0];
    

    There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations

提交回复
热议问题