在我下面的代码中,当我将它用作 c 文件时它会编译并运行,但当我将它用作 cpp 文件时会出错。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct ploc_t {
int num;
ploc_t *right;
};
ploc_t *create_ploc(int *point , int *triangles, int n , int m){
// just for testing
ploc_t *result;
result=(ploc_t*)malloc(sizeof(ploc_t));
return result;
}
int main( )
{
int points[1][2];
int triangles[1][2];
points[0][1]=2;
points[0][2]=4;
triangles[0][1]=8;
triangles[0][2]=6;
create_ploc(points,triangles,3,4);
}
我在使用 cpp 文件时遇到的错误是:
无效的候选参数是:plot_t(int*,int*,int,int)
为什么会出现这个错误?如何解决?
最佳答案
在这种情况下,C 和 C++ 之间的区别在于,在 C 中,您正在做的事情(将指向 int[2]
的指针传递给期望指向 int< 的指针的函数
) 是合法的,尽管不鼓励这样做,而在 C++ 中,您不允许这样做。所以在C中,编译器会发出警告。如果您没有使用 -Wall
标志,您可能看不到警告。在 C++ 中,您是否使用 -Wall
并不重要(尽管您总是应该这样做)因为这是一个错误并且编译将失败。
作为参数传递的数组“衰减”为指向数组元素类型的指针。 (这不是数组衰减为指针的唯一情况,但它与这个问题相关。)您的数组类型为 int[][2]
,因此元素类型为 整数[2]
。因此,当您将它们用作参数时,它们会衰减为 int(*)[2]
,这是 C/C++ 表达“指向双元素整数数组的指针”的特殊方式。
指向 int
的指针和指向 int[2]
的指针有什么区别?一个重要的区别是目标的大小:
int a[2];
int* p = a;
p++;
// p now points to a[2]; it was incremented by sizeof(int)
int aa[10][2];
int(*pp)[2] = aa;
pp++;
// pp now points to aa[2]; it was incremented by sizeof(int[2])
与其纠结于指向数组指针的语法,不如将函数定义为接受二维数组:
ploc_t *create_ploc(int points[][2], int triangles[][2], int n , int m);
但是您可以使用完全相同的语义写出衰减的类型:
ploc_t *create_ploc(int (*points)[2], int (*triangles)[2], int n , int m);
关于c++ - 通过引用传递在 C 中有效,但不适用于此代码的 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425833/