Reputation: 185
In my below code , It compiles and runs when I use it as a c file , but gives an error when I run it as cpp file.
#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);
}
Error which I get in when using cpp file is :
Invalid arguments candidates are: plot_t(int*,int*,int,int)
Why is this error? and how can it be resolved?
Upvotes: 0
Views: 121
Reputation: 241671
The difference between C and C++ in this instance is that in C, what you're doing (passing a pointer to int[2]
to a function expecting a pointer to int
) is legal although discouraged, whereas in C++ you're not allowed to do it. So in C, the compiler will issue a warning. If you're not using the -Wall
flag, you might not see the warning. In C++, it doesn't matter whether you used -Wall
or not (although you always should) because it's an error and the compile will fail.
Arrays passed as parameters "decay" to a pointer to the array element type. (That's not the only case in which arrays decay to pointers, but it's the one relevant to this question.) Your arrays are of type int[][2]
, so the element type is int[2]
. Consequently, when you use them as arguments, they decay to int(*)[2]
, which is C/C++'s idiosyncratic way of saying "a pointer to a two-element array of ints".
What's the difference between a pointer to an int
and a pointer to an int[2]
? One important difference is the size of the target:
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])
Rather than fighting with the syntax for pointer to arrays, you probably want to define you function to accept two-dimensional arrays:
ploc_t *create_ploc(int points[][2], int triangles[][2], int n , int m);
But you could, with exactly the same semantics, write out the decayed types:
ploc_t *create_ploc(int (*points)[2], int (*triangles)[2], int n , int m);
Upvotes: 2
Reputation: 26
Looking at your main:
int points[1][2];
int triangles[1][2];
"points" and "triangles" are two-dimensional arrays. The first two arguments to create_ploc() are pointers to integers. Passing these two-dimensional arrays directly into the function is not passing a pointer. I'm not sure exactly what you want to do, but a couple of ways to solve this are:
1)
int points[1];
int triangles[1]; // both one-dimensional arrays of ints (int*)
2)
create_ploc(points[0],triangles[0],3,4); // passing in a one-dimensional array of ints (int*)
Upvotes: 0