C++ * vs [] as a function parameter

随声附和 提交于 2019-12-19 18:20:54

问题


What is the difference between:

void foo(item* list)
{
    cout << list[xxx].string;
}

and

void this(item list[])
{
    cout << list[xxx].string;
}

Assuming item is:

struct item
{
    char* string;
}

With the pointer pointing to the first of an array of chars

and list is just an array of items...


回答1:


To the compiler, there is no difference.

It reads different though. [] suggests you want to pass an array to the function, whereas * could also mean just a simple pointer.

Note that arrays decay to pointers when passed as parameters (in case you didn't already know).




回答2:


They are the same - completely synonymous. And the second is item list[], not item[]list.

However it is customary to use [] when the parameter is used like an array and * when it's used like a pointer.




回答3:


FYI:

void foo(int (&a)[5]) // only arrays of 5 int's are allowed
{
}

int main()
{
  int arr[5];
  foo(arr);   // OK

  int arr6[6];
  foo(arr6); // compile error
}

but foo(int* arr), foo(int arr[]) and foo(int arr[100]) are all equivalent



来源:https://stackoverflow.com/questions/10760893/c-vs-as-a-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!