问题
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