2

i'm still new to arduino and also to C++ and have a short question. What i want to do is to write a function (in my case to parse the query-string of an URL) to get the parameter names and values (varying number of parameters).

My function looks like the following:

String function readParams()
{
 String params[x]; // x: number of params
 // fill params[0]... params[x] with parameter names
 return params;
}
void loop()
{
 // do some stuff
 String params[x] = readParams();
 for(int i=0; i < x; i++)
 {
 debug(params[i]);
 }
}

What is the correct return-type for the readParams() function in this case? And how to access the params in the main (loop) -function?

I hope the code makes it clear what i want to do.

Thanks, Marius

asked Mar 13, 2018 at 14:02

2 Answers 2

2

Some tips:

  1. Don't use String.
  2. Use char * and slice the string in-place.
  3. Pass a pointer to an array of pointers and fill that with pointers to the portions of the string you have sliced.
  4. Return the number of entries in the array you used.

I do something similar in my CLI library. I use a custom "getWord" function, but similar can be done with strtok().

You can read more about working with C strings here.

answered Mar 13, 2018 at 14:09
2

I'm inclined to agree with Majenko that you shouldn't use String in the first place, but if you want to, you can pass by reference:

const int numParams = 2;
void readParams(String (& params) [numParams])
 {
 params [0] = "foo";
 params [1] = "bar";
 }
void setup() 
{
 Serial.begin (115200);
 String params [numParams];
 readParams (params);
 for (int i = 0; i < numParams; i++)
 Serial.println (params [i]);
}
void loop() { }

An easier thing is to make the parameters a global variable.

answered Mar 13, 2018 at 21:59
2
  • what if number of parameters is not known in the beginning ? how would you initialize numPaams then ? Commented May 25, 2020 at 12:18
  • Typically you would use new and make an array of whatever it is you want to make multiple copies of. Or you could consider the STL (Standard Template Library) which supports things like vectors. Commented May 26, 2020 at 6:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.