Appending an int to a char* array

I am having a difficult time adding an integer into a char* array. How do I accomplish this, preferably without extra lines?

Code:

char *topRight[] = {durations[durationsIndex] + " ms", durations[durationsIndex] + " ms", durations[durationsIndex] + " ms", voltage + " mv"};

Error:

error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
 char *topRight[] = {durations[durationsIndex] + " ms", durations[durationsIndex] + " ms", durations[durationsIndex] + " ms", voltage + " mv"};

Why? It makes no sense. If it's a char array it should only hold chars, and an int array, only an int.

It looks like you want to add an int that has been converted to a char string to the array. So do that first.

It's a char* array which essentially holds strings. I'm looking to combine an int with a string to output to an lcd. Doing this in c++ or python is a non-issue, but I can't seem to figure it out for C.

sprintf()

I don't think so, not in C++ anyway. If you compiled this code on an Arduino it is C++.

C++ does not perform that kind of automatic type conversion.

Kudos for not using the String class on an Arduino...

Apologies, was thinking about combining strings and integers with iostream in C++. Thanks for the help!

Unfortunately I couldn't get this to work. When I printed the array to the lcd, the parts of the array that contained sprintf() were empty. This leads me to believe that sprintf() never updated the spots in the array.

I updated

char *topRight[] = {durations[durationsIndex] + " ms", durations[durationsIndex] + " ms", durations[durationsIndex] + " ms", voltage + " mv"};

With

char *topRight[4];

sprintf(topRight[0], "%d ms", durations[durationsIndex]);
sprintf(topRight[1], "%d ms", durations[durationsIndex]);
sprintf(topRight[2], "%d ms", durations[durationsIndex]);
sprintf(topRight[3], "%d mv", voltage);

You have to allocate the char arrays first, before anything can be written to them.

char topRight0[40], topRight1[50], ...
char *topRight[2] = { topRight0, topRight1 };

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.