Jump to content

Archived

This topic is now archived and is closed to further replies.

Netshroud

[Version 1] [coding] Strings Help

Recommended Posts

How do I concatenate and pass strings? From what I understand, hardcoded strings have to be PSTR()'ed so that they end up on the Teensy, and they then run from program memory, such as:

typeString( PSTR("Hello, World!") );

Reading that string seems to be painful. Currently, my typeString function is defines as:

void typeString(const char* string);

Except it appears not to be a standard character array. From what I've seen, char[0] should return 'H', but it isn't, and to return each character in the string, I need to use:

char c;
while ( c = pgm_read_byte(string++) )
{
// Do Something
}

Which is complex enough for me. But how do I concatenate two strings, such as PSTR("Hello, ") and PSTR("World!") ?

I'm currently trying:

char* str1 = PSTR("Hello, ");
char* str2 = PSTR("World!");
char* helloworld = malloc( strlen(str1) + strlen(str2) + 1);
strcpy(helloworld, str1);
strcat(helloworld, str2);

This causes all code after this to not execute, leading me to think it's segfaulting.

I've tried sprintf, but I get the following compiler error:

strings.c:46: warning: implicit declaration of function 'sprintf'

strings.c:64: warning: incompatible implicit declaration of built-in function 'sprintf'

What am I doing wrong, and how do I do it right?

________________________________

Edit: OK, I've made some progress:

PGM_P hello = PSTR("Hello, ");
PGM_P world = PSTR("World!");

char* newstr = malloc( strlen_P(hello) + strlen_P(world) + 1);

strcpy_P(newstr, hello);
strcat_P(newstr, world);

typeString(newstr);

However this only prints out "World!". The first string is getting lost somewhere.

Share this post


Link to post
Share on other sites

Sorry, didn't realize you were using C, please ignore this :)

Share this post


Link to post
Share on other sites

Azn suggested in IRC simply typing two strings in a row, as concatenation is an expensive task. I may have to go with that.

Share this post


Link to post
Share on other sites

Can't you just do

string a = "Hello, ";
string b = "world!";

string hw = a+b;

?

Share this post


Link to post
Share on other sites

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...