Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Output parameters with arrays in one function with Arduino and C ++

I have a problem with the initialization with various parameters in my function.
It works if I have created an array int params [] = {...}. However, it doesn’t work if I want to write the parameters directly into the function.

declaration (in the .h)

void phase_an(int led[]);

in the .cpp

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void RS_Schaltung::phase_an(int led[])
{
  for (size_t i = 0; i < LEN(led); i++) {
    digitalWrite(led[i], HIGH);
  }
}

if I try this way, it won’t work. I would like it to be like that. But I couldn’t find anything about it on the internet. …:
in the Arduino sketch:

RS.phase_an(RS.ampelRot, RS.ampelGelb, ..... );    <--- is there a way to do it like that?

what amazes me is that it works this way:

int p_an [5] = {RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb};
...................
RS.phase_an (p_an);

does anyone have a suggestion?

>Solution :

There are several ways of making a function accepting a variable number of arguments here.

However, in your current code there is a problem: when you pass a native array of unknown size as argument of a function (e.g. void f(int a[])), the argument will be managed a pointer to an array, and there is no way inside this function to know the real length of that array. I don’t know how LEN() is defined, but chances are high that it doesn’t works well in your code.

A safer and more practical alternative is to use a vector<int> instead:

#include <iostream>
#include <vector>
using namespace std;

void f(const vector<int>& a){
    for (int i=0; i<a.size(); i++) {
        cout<<a[i]<<" ";
    }
    cout<<endl; 
}

int main() {
    vector<int> test={1,2,3,4}; 
    f(test); 
    f({1,2,3,4});
    return 0;
}

In this case, you can pass your multiple values between bracket in the function call (e.g. ({RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb})and C++ will automatically convert it to a vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading