3

I am having a bit of difficulty with the Arduino project I am currently working on.

The purpose of the function I am developing is to take in a char array variable received via an NRF wireless module and separate this into 2 different string variables. The first 13 characters into one string, and the remaining into another.

void receiveData(char* receivedData){ // Function to place the received data into the correct variable.
  for(int i = 0;i < sizeof(receivedData);i++){
    if(i < 13){
      String variableName = variableName + receivedData[i]; // Builds a string of the variablename.
    }
    else{
      String value = value + receivedData[i]; // Builds a string of the value.
    }   
  } 

I have worked through a few different ways but no luck.

Any help will be greatly appreciated, Thank you!

Mehdi Mostafavi
  • 880
  • 1
  • 12
  • 25
Paul James
  • 121
  • 2
  • 7
  • Does this answer your question? [C++: sizeof for array length](https://stackoverflow.com/questions/2993646/c-sizeof-for-array-length) – Timo Mar 18 '20 at 14:24
  • 1
    variableName stays in the scope of your if loop, so once you enter your for loop again, all changes made to variableName will dissapear. You should declare value and variableName outside your for loop (String variablename, value;) – Arno Deceuninck Mar 18 '20 at 14:24
  • 1
    `sizeof(receivedData)` is the same as `sizeof(char*)`, which will be 4 or 8 depending on the platform (probably 4 on an Arduino). You need to pass the size to the function. – molbdnilo Mar 18 '20 at 14:24

1 Answers1

3
String variableName = variableName + receivedData[i];

Here you are defining the variable in every iteration of the loop. You should declare the variable before the loop:

String variableName;
for () {
    variableName = whatever;
}

In addition sizeof(receivedData) will only give you size of the pointer, not the size of the string that you probably expect.

pablo285
  • 2,460
  • 4
  • 14
  • 38
  • I see that, thankyou. The problem I am getting is say I pass the char array of "voltageBefore34", when I serial print and monitor this output of variableName, I only get 'vvo' and I am unsure why. – Paul James Mar 18 '20 at 14:32
  • 1
    Can't really answer that, I strongly suggest that you use a debugger and do a step-by-step analysis of what your loop is doing. – pablo285 Mar 18 '20 at 14:37
  • I have got it working, Pablo. Thank you very much for your help. much appreciated! – Paul James Mar 18 '20 at 14:37