如何在C ++中通过引用或值或指针传递数组? [英] How are arrays passed in C++ by reference or value or by pointer?

查看:52
本文介绍了如何在C ++中通过引用或值或指针传递数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个尝试学习C ++的初学者.道歉,如果我的问题结构不正确?我在处理数组时发现,我可以通过函数来​​操纵存储在数组中的值,而无需使用& 或通过引用符号传递.我不明白这怎么可能,因为缺少& 符号意味着它是按值传递的,并且创建了一个可操纵的副本.

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?

侧面说明:为什么在将2D数组传递给函数时必须指定列大小?

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

推荐答案

C数组衰减到指针.

某些声明也具有误导性

void foo(const char name[42]);

实际上是

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]);

这篇关于如何在C ++中通过引用或值或指针传递数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆