在下面的代码中,当我将其用作ac文件时,它会编译并运行,但是当我将其作为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
(尽管您总是应该这样做)都没有关系,因为这是一个错误,并且编译将失败。
作为参数“衰减”传递到指向数组元素类型的指针的数组。(这不是数组衰减到指针的唯一情况,但这是与此问题相关的一种情况。)您的数组是type int[][2]
,因此元素类型是int[2]
。因此,当您将它们用作参数时,它们会衰减为int(*)[2]
,这是C / C ++特有的说法:“一个指向由两个元素组成的整数数组的指针”。
指向anint
的指针和指向an的指针有什么区别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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句