Difference between [square brackets] and *asterisk

后端 未结 5 2108
遇见更好的自我
遇见更好的自我 2020-11-27 04:03

If you write a C++ function like

void readEmStar( int *arrayOfInt )
{
}

vs a C++ function like:

void readEmSquare( int arrayOfInt[] )
{
}
         


        
5条回答
  •  Happy的楠姐
    2020-11-27 04:31

    When you use the type char x[] instead of char *x without initialization, you can consider them the same. You cannot declare a new type as char x[] without initialization, but you can accept them as parameters to functions. In which case they are the same as pointers.

    When you use the type char x[] instead of char *x with initialization, they are completely 100% different.


    Example of how char x[] is different from char *x:

    char sz[] = "hello";
    char *p = "hello";
    

    sz is actually an array, not a pointer.

    assert(sizeof(sz) == 6);
    assert(sizeof(sz) != sizeof(char*)); 
    assert(sizeof(p) == sizeof(char*));
    

    Example of how char x[] is the same as char *x:

    void test1(char *p)
    {
      assert(sizeof(p) == sizeof(char*));
    }
    
    void test2(char p[])
    {
      assert(sizeof(p) == sizeof(char*));
    }
    

    Coding style for passing to functions:

    It really doesn't matter which one you do. Some people prefer char x[] because it is clear that you want an array passed in, and not the address of a single element.

    Usually this is already clear though because you would have another parameter for the length of the array.


    Further reading:

    Please see this post entitled Arrays are not the same as pointers!

提交回复
热议问题