通过引用传递数组?

7

我是一名初学者,最近遇到了这个问题。

以下代码显然可以工作:

void setvalues(int *c, int *d)
{
    (*c) = 1;
    (*d) = 2;
}
int main()
{
    int a, b;
    setvalues(&a, &b);
    std::cout << a << b;
}

所以为什么会返回错误?Visual C++ 2010 error:
'C2664: 'setvalues' : cannot convert parameter 1 from 'int (*)[2]' to 'int *[]'
void setvalues(int *c[2], int *d[2])
{
   (*c[1]) = 1;
   (*d[1]) = 2;
}
int main()
{
    int a[2], b[2];
    setvalues(&a, &b);
    std::cout << a[1] << b[1];
}

指向数组的指针有什么不同?我搜索了一下,但没有找到相关内容。

cdecl 是你的好朋友。 - Robᵩ
3个回答

6

int *a[2] 这个类型表示的是一个数组,它包含了两个指向 int 的指针,而表达式 &a 在定义 int a[2] 后则表示指向一个包含了两个 int 的数组的指针。这两者都是不同的类型,且它们之间没有转换。正如 Vlad 已经提到的,为了提供正确的类型,你需要加上括号:

void setvalues( int (*c)[2] )

或者您可以在C ++中使用实际的引用:

void setvalues( int (&c)[2] )

在后一种情况下,您不需要在setvalue函数内使用取地址操作符或对其进行解引用:
int a[2];
setvalues(a); // this is a reference to the array

一个更简单的编写代码的方法是使用 typedef:
typedef int twoints[2];
void setvalue( toints& c );
int main() {
   twoints a; // this is int a[2];
   setvalue(a);
}

我现在明白了,谢谢。我假设对于字符串数组也是一样的吗? - NoToast
@user1867129:这取决于您所说的“字符串”是什么意思,但对于所有类型,语法都是一致的。如果您想使用指向数组的指针,则必须使用倒置的括号(在 int (*a)[2] 中,括号实际上将所有位于括号外部的内容分组:a 是指向括号外描述的类型的指针)。 - David Rodríguez - dribeas

3

需要使用void setvalues(int (&c)[2], int (&d)[2])来进行引用传递。调用者必须使用setvalues(a, b);,否则你最多只能通过指针传递。


2
这是修复它的方法:
void setvalues(int c[], int d[])
{
   c[1] = 1;
   d[1] = 2;
}
int main()
{
    int a[2],b[2];
    setvalues(a, b);
    std::cout<<a[1]<<b[1];
}

当你像这样声明一个数组:int a[2], b[2];,那么ab已经是这些数组的起始指针。
当你执行a [0]时,这时你实际上是在访问数组中的元素,通过偏移量访问数组。例如a [1]等同于*(a+1)
参考:http://www.cplusplus.com/doc/tutorial/arrays/

1
这并不完全正确,因为它与通过指针传递相同。那个数组的长度是多少?它在编译时执行吗?不是的。 - user405725

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接