【问题标题】:Different syntax of passing an array to a function in C++在 C++ 中将数组传递给函数的不同语法
【发布时间】:2021-03-14 23:26:12
【问题描述】:
#include <stdio.h>

void test2(int (&some_array)[3]){
  // passing a specific sized array by reference? with 3 pointers?
}

void test3(int (*some_array)[3]){
  // is this passing an array of pointers?
}

void test1(int (some_array)[3]){
  // I guess this is the same as `void test1(some_array){}`, 3 is pointless.
}

int main(){
  //
  return 0;
}

以上三种语法有什么区别? 我在每个部分都添加了 cmets,以使我的问题更加具体。

【问题讨论】:

  • 这能回答你的问题吗? Function pointer as an argument
  • 最后一个怎么3没用?
  • 这段代码到底想做什么?这不是你见过的东西。
  • 探索c和c++的语法
  • 两种语言都有很多语法,尤其是 C++。并非它的所有排列都是有用的。

标签: c++


【解决方案1】:
void test2(int (&some_array)[3])

这是传递对 3 个ints 数组的引用,例如:

void test2(int (&some_array)[3]) {
    ...
}

int arr1[3];
test2(arr1); // OK!

int arr2[4];
test2(arr2); // ERROR!
void test3(int (*some_array)[3])

这是传递一个指向 3 个ints 数组的指针,例如:

void test3(int (*some_array)[3]) {
    ...
}

int arr1[3];
test3(&arr1); // OK!

int arr2[4];
test3(&arr2); // ERROR!
void test1(int (some_array)[3])

现在,事情变得有点有趣了。

括号在这种情况下是可选的(在引用/指针情况下它们不是可选的),所以这等于

void test1(int some_array[10])

这又只是语法糖

void test1(int some_array[])
(是的,数字被忽略了)

这又只是语法糖

void test1(int *some_array)

所以,不仅数字被忽略,而且它只是一个简单的指针被传入。并且任何固定数组都会衰减为指向其第一个元素的指针,这意味着 any 数组可以被传入,即使声明表明只允许 3 个元素,例如:

void test1(int (some_array)[3]) {
    ...
}

int arr1[3];
test1(arr1); // OK!

int arr2[10];
test1(arr2); // ALSO OK!

int *arr3 = new int[5];
test1(arr3); // ALSO OK!
delete[] arr3;

Live Demo

【讨论】:

  • 使用reference to an array of 3 ints 比使用pointer to an array of 3 ints 有什么好处吗?有区别吗?
  • @Dan 除了指针可以为 NULL 而引用不能为空外,它们之间没有其他实际区别。更喜欢使用引用,除非你真正需要一个指针。
【解决方案2】:

在您的代码中,test3 是传递指向数组的指针的正确方法,如果您愿意的话。

void foo(int (*some_array)[3])
{
    for (size_t i = 0; i < 3; ++i) {
        printf("some_array[%zu]: %d\n", i, (*some_array)[i]);
    }
}

int main()
{
    int a[3] = { 4, 5, 6 };

    foo(&a);

    return 0;
}

运行此代码会返回您所期望的结果:

some_array[0]: 4
some_array[1]: 5
some_array[2]: 6

【讨论】:

  • int (*some_array)[3],sizeof可以安全使用吗?也是int (some_array)[3]int some_array[3]{} 一样吗?
  • 我刚刚测试过,你可以使用sizeof(*some_array),它返回12(因为我的机器上一个int是4)。至于你的第二个问题,int a[3] 相当于int (a)[3]
猜你喜欢
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
  • 2012-07-25
相关资源
最近更新 更多