// Defined three array arr0,arr1,arr2
int arr0[] = {0, 0, 0, 0, 0, 0, 0, 0};
int arr1[] = {0, 0, 0, 0, 0, 0, 0, 0};
int arr2[] = {0, 0, 0, 0, 0, 0, 0, 0};
//cord function takes binary number array as input and returns decimal
//number to a single variable as output
int cord(int a[]) {
int v = 0;
for (int i = 0; i < 8; i++)
{
int p = 1;
for (int j = 0; j < i; j++)
{
p = p * 2;
}
v = v + a[i] * p;
}
return v;
}
//function bcord takes input row & col and updates the value in arr0,arr1,arr2 to 1 wherever
// there is some value in the row and column coordinate Eg.2,0 will make 2nd index of arr0
// to 1 or 2,1 will make 2nd index of arr1 to 1
int bcord(int row[], int col[])
{
int n = sizeof(col) / sizeof(col[0]);
for (int i = 0; i < n; i++)
{
int j;
if (col[i] == 2)
{
j = row[i];
arr2[j] = 1;
}
if (col[i] == 1)
{
j = row[i];
arr1[j] = 1;
}
if (col[i] == 0)
{
j = row[i];
arr0[j] = 1;
}
}
int led0 = cord(arr0);
Serial.print(led0);
int led1 = cord(arr1);
Serial.println(led1);
int led2 = cord(arr2);
Serial.println(led2);
return 0;
}
void setup()
{
Serial.begin(9600);
int row[] = {0, 0, 2, 2, 1};
int col[] = {0, 1, 0, 1, 1};
bcord(row, col);
}
void loop() {}
// Output expected is decimal numbers which are stored in led0, led1 and led2 on the serial
// monitor
1 Answer 1
In C++, you cannot pass an array as a parameter to a function. When you write the function prototype
int bcord(int row[], int col[], int n)
the compiler considers it a synonym of:
int bcord(int *row, int *col, int n)
In other words, both row
and col
are pointers, not arrays.
When you call the function like this:
bcord(row, col);
the compiler implicitly converts the call into this:
bcord(&row[0], &col[0]);
In other words, you are really passing pointers to the first element of each array. This is a standard language behavior called "decay to pointer".
When I compile your code with warnings enabled, I get the following:
In function 'int bcord(int*, int*)':
warning: 'sizeof' on array function parameter 'col'
will return size of 'int*' [-Wsizeof-array-argument]
int n = sizeof(col) / sizeof(col[0]);
^
arr-ind.ino:31:30: note: declared here
int bcord(int row[], int col[])
^
Thus the compiler is telling you what is wrong. The variable n
is not
what you expect.
The standard solution is to pass the size of the array from the caller:
move the definition of n
to setup()
, define bcord()
as:
int bcord(int row[], int col[], int n)
and call it as
bcord(row, col, n);
led0
is 5,led1
is 7 andled2
is 0.