Home > Back-end >  Concatenation of chars
Concatenation of chars

Time:11-28

I need to concatenate to chars and send it as argument to function, but strcat move concatenated chars to first char. I need a method that return concatenated char. Or if I can do it in different way how can I do it?

void abca(char *a)
{
  Serial.println(a);
}


void setup()
{
  Serial.begin(9600);

  char *bb = "1";
  char *aa = "2";
  abca(strcat(aa, bb));

}

Edit: I'm creating program for Arduino, and I can't use strings. Strings use a lot of memory. Unfortunately Arduino have only 2kB

CodePudding user response:

There are a few problems with your code. First of all, you are using non-const pointers to const arrays:

char *bb = "1"; // "1" is a char constant array
char *aa = "2"; // so it needs a pointer to constant memory

When you fix that your function calls will fail because they need non-const arrays.

One fix is to create a non-const array to receive your concatenated string:

// should be const because it is not modified
void abca(char const* a)
{
    Serial.println(a);
}

void setup()
{
    Serial.begin(9600);

    // char const array decays to pointer to const char
    char const* bb = "1";
    char const* aa = "2";

    // can't concatenate into constant memory
    // abca(strcat(aa, bb));

    // So make some writable memory and concat to that
    char buffer[32]; // long eough for the combined text

    strcpy(buffer, bb);
    strcat(buffer, aa);

    abca(buffer);
}

If you don't know how big the resulting string is you may need to allocate buffer dynamically to make sure it is big enough.

CodePudding user response:

If you are able to change the function to

void abca(const char *a)

Then you could use a std::string at the calling site and the c_str() method:

int main()
{
    std::string a = "aa";
    std::string b = "bb";
    abca((a   b).c_str());
}

Note that the overloaded operator is used for concatenation. Better still, if you can change the function to

void abca(const std::string& a)

(note that the body of the function is unchanged), you can write

abca(a   b);

at the calling site. All standard C , and no memory leaks or undefined behaviour either! std::string might get some bad press but it does epitomise the power of C .

  • Related