A
Arduino2d ago
Tari

char to char* adds characters on the end

Hi, I'm using this code to pull data from a section of a char* string, and pass a single character to the U8G2 drawStr() method. The drawStr method will only accept a const char*, so I need to convert the char I get from the char* array into another char*. This, for some reason; adds the characters xV? to the end of the desired output when displaying with U8G2 drawStr.
char *charset = ".,!?ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\':;()";
const char *key1Char = new char(charset[4]);
const char *key2Char = new char(charset[5]);
const char *key3Char = new char(charset[6]);
const char *key4Char = new char(charset[7]);

u8g2.drawStr(57, 22, key1Char);
u8g2.drawStr(29, 37, key2Char);
u8g2.drawStr(84, 40, key3Char);
u8g2.drawStr(56, 55, key4Char);
char *charset = ".,!?ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\':;()";
const char *key1Char = new char(charset[4]);
const char *key2Char = new char(charset[5]);
const char *key3Char = new char(charset[6]);
const char *key4Char = new char(charset[7]);

u8g2.drawStr(57, 22, key1Char);
u8g2.drawStr(29, 37, key2Char);
u8g2.drawStr(84, 40, key3Char);
u8g2.drawStr(56, 55, key4Char);
1 Reply
sven
sven2d ago
The issue is that you're creating single characters, not null-terminated strings. When you use new char(charset[4]), you're allocating a single character without a null terminator (\0). The drawStr() function expects a null-terminated C-string, so it keeps reading memory beyond your single character until it happens to find a null byte, which is why you're seeing garbage characters. - If U8G2 has a drawChar method : // Check if this exists in your U8G2 library u8g2.drawGlyph(57, 22, charset[4]); // or u8g2.drawChar(57, 22, charset[4]); - Use stack-allocated arrays : char *charset = ".,!?ABCDEFGHIJKLMNOPQRSTUVWXYZ"':;()"; char key1Char[2] = {charset[4], '\0'}; char key2Char[2] = {charset[5], '\0'}; char key3Char[2] = {charset[6], '\0'}; char key4Char[2] = {charset[7], '\0'}; u8g2.drawStr(57, 22, key1Char); u8g2.drawStr(29, 37, key2Char); u8g2.drawStr(84, 40, key3Char); u8g2.drawStr(56, 55, key4Char);

Did you find this page helpful?