How are arrays passed in C++ by reference or value or by pointer?

放肆的年华 提交于 2021-02-19 09:32:19

问题


I am a beginner trying to learn C++. Apologies if my question is not structured properly? I was working with arrays and found out that I can manipulate the values stored in an array through a function without using the & or pass by reference sign. I don't understand how this is possible as the lack of & sign means that it is passed by value and a copy is made which is manipulated.

Elsewhere, I read that arrays are passed by pointers if this is the case I didn't use any explicit dereferencing to manipulate the data. Can you please explain what is actually happening when I pass an array?

Side note: Why is it that I have to specify column size when passing a 2D array into a function?


回答1:


C-array decays to pointer.

Some declarations are misleading too

void foo(const char name[42]);

is in fact

void foo(const char* name);

Only reference/pointer (ugly syntax :/) allow to keep size:

void foo(const char (&name)[42]);
void foo(const char (*name)[42]);


来源:https://stackoverflow.com/questions/44696363/how-are-arrays-passed-in-c-by-reference-or-value-or-by-pointer

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