Hello im trying to write this program which replace each negative number with -1 and positive with 1 but an error :
[Error] cannot convert 'int ()[3]' to 'int ()[100]' for argument '1' to 'void replace(int (*)[100], int, int)'
what does that mean ??
#include<iostream>
using namespace std;
void replace(int Arr[][100],int rsize, int csize)
{
for(int r=0;r<rsize;r++)
{
for (int c=0;c<csize;c++)
{
if (Arr[r][c]>0) Arr[r][c]=1;
else if (Arr[r][c]<0) Arr[r][c]=-1;
else Arr[r][c]=0;
}
}
}
int main()
{
int a[4][3]={
{2,0,-5},
{-8,-9,0},
{0,5,-6},
{1,2,3}};
replace(a,4,3);
for(int i=0;i<4;i++)
for (int j=0;j<3;j++)
cout<<a[i][j]<<" ";}cout<<endl;
system ("pause");
return 0;
}
You declared function
void replace(int Arr[][100],int rsize, int csize)
- it expects 2D array, with 'inner' dimension being 100. Then you pass to itint a[4][3]
which has 'inner' dimension 3. Compiler can't convert it. Those dimensions are used to calculate memory position shift when usingArr[x][y]
(it is equivalent to*(Arr + x * 100 + y)
. That's why compiler can't assign array with 3 to array with 100.If you want your
replace
to work with any dimension change it to:void replace(int* Arr,int rsize, int csize)
. Then use*(Arr + r*csize + c)
to access fields instead ofArr[r][c]
Even better solution: you tagged this question as C++ - use C++ library :) -
std::vector<std::vector<int> >
orstd::array
(C++11)