I've got an array of char* with serial data that I'm trying to remove ':' from. I have tried to iterate through the char*, find and remove any colons but it just comes out as garbage.
char* espData[15]; // pull data from serial and tokenize with strtok > feed to espData for(int x = 0; x < index-1; x++){ size_t nullTerm = strlen(espData[x]); espData[x][nullTerm - 1] = '\0'; char* output for(size_t i = 0; i < strlen(espData[x]); ++i){ if(espData[x][i] != ':') output += espData[x][i]; } espData[x] = output; Serial.println(espData[x]); }Moving the null character works fine (I wanted to get rid of the last character in every string). Most of the answers I found for general C++ used std::string which we don't have access to.
- Arithmetic on a
char*does nothing to its contents.Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2016-06-15 01:32:17 +00:00CommentedJun 15, 2016 at 1:32 - the comment
tokenize with strtoksuggests your code uses strtok, which would be one (probably bloated) solution - yet your code doesn't use strtok!!?Jaromanda X– Jaromanda X2016-06-15 03:53:38 +00:00CommentedJun 15, 2016 at 3:53 espData[x][nullTerm - 1] = '\0';is redundant codeJaromanda X– Jaromanda X2016-06-15 03:55:08 +00:00CommentedJun 15, 2016 at 3:55- @Jaromanda Actually, it overwrites the last character in the string - or underflows the buffer if
nullTermis0!John Burger– John Burger2016-06-15 10:11:28 +00:00CommentedJun 15, 2016 at 10:11 - @JohnBurger - of course you're rightJaromanda X– Jaromanda X2016-06-15 10:23:25 +00:00CommentedJun 15, 2016 at 10:23
1 Answer1
You've assumed that achar * is some kind of string object, since you've got the following line of code:output += espData[x][i];, and then laterespData[x] = output;
It quite simply doesn't work like that. At best you can pointoutput insideespData[x] and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.
Please consider the following code instead:
char* espData[15];for(int x = 0; x < index-1; x++){ size_t nullTerm = strlen(espData[x]); // Get current length char* output = espData[x]; // Start of string for (size_t i = 0; i < nullTerm; ++i){ if(espData[x][i] != ':') { // If it's NOT a colon *output++ = espData[x][i]; // Copy character 'up' } // if // If it WAS a colon, then // output does NOT get incremented } // for *output = '\0'; // End string off with NUL Serial.println(espData[x]);} // for- That works perfectly, thank you! I have never been great with pointersTri42– Tri422016-06-15 22:05:14 +00:00CommentedJun 15, 2016 at 22:05
- @Tri42 I just finished a pointer-post on another question. Take a look:arduino.stackexchange.com/a/25317/22924John Burger– John Burger2016-06-16 03:17:27 +00:00CommentedJun 16, 2016 at 3:17
Explore related questions
See similar questions with these tags.
