Serial.write(ptr,len) ->increment ptr while applying a function


I was wondering if it is possible to apply a function to a char as it is being written with Serial.write. Something as follows:

char buffer[20]={2,3,4,5,6,7,8,9.....}; char ptr = &buffer[0]; char len = 20;

char * updatevalue(*char ptr){ uint8_t c = *ptr*2; return &c; }


Not sure if this is possible, can anybody help out?



Not like that. You are returning a pointer to a local variable.

This is incredibly convoluted. What about a "for" loop that just steps through the array?

If you weren't submitting an entry in the "obsfuscated C competition" I would mark you down heavily for that code. It's almost incomprehensible. No offence. :)

char * updatevalue(*char ptr){
uint8_t c = *ptr*2;
return &c;

Did you bother even trying to compile this?

Let me try ...

char buffer[20]={2,3,4,5,6,7,8,9};
char ptr = &buffer[0];


sketch_may03e:1: error: invalid conversion from 'char*' to 'char'

do you want to apply the function to the first element only or to all the elements?

your code returns the address of the local var c on the stack as the start of the array. That is a recipe for disaster

this is a refactored version that only changes the first char of the array. (stayed as close to your code as possible)

char buffer[20]={2,3,4,5,6,7,8,9.....};
char* ptr = &buffer[0];     //  Patched here
char len = 20;

char * updatevalue(*char ptr){
uint8_t c = *ptr*2;
return ptr;   // and here


all elements

for (int i=0; i<len; i++)
  char c = buffer[i] * 2;  // keep original content intact? otherwise use buffer[i] *= 2;  Serial.write(buffer[i];

After you’ve been bashed so hard:
Your original question “increment ptr while applying a function”
→ that’s possible of course:

int get2Value(char* p) { return ( (*p) << 1) ; }

char buffer[20]={2,3,4,5,6,7,8,9};
char* ptr = buffer;     
char len = 10;
void setup() 
  while (len-- != 0 )
     Serial.print(get2Value(ptr++)); Serial.print(' ');  // prints "4 6 8 10 12 14 16 18 0 0 "

This sample does not change the buffer content, but it increments ptr after it has been used to call a function.

Hope you get the other hints, too :wink:

Well, the reason I brought it up is because I have seen some code where people create a class that inherits from print.h, they create their own function for write to execute a function on the chars. I thought this might be a way to get around that.