1

I'm trying to concatenate two dynamic c arrays (containing strings) using pointers. I looked up a bunch of things online that use strcat, but I need to learn how to use pointers to do this. I'm not exactly clear on what a dynamic c array is anyway, I just know I have to use "new" for it. Here's my current code that won't compile:

#include <iostream>
using namespace std;
#define MAX_CHAR 50


void append(char*, char*);

int main()
{
    char *str1 = new char[MAX_CHAR];
    char *add1 = new char[MAX_CHAR];
    str1 = "This string";
    add1 = " add this one";

    append(str1, add1);

    cout << str1;

    delete [] add1;
    delete [] str1;

    return 0;
}

void append(char *str, char *add)
{
   while(*str != '\0')
      str++;

   while(*add != '\0')
   {
      *str = *add;
      add++;
      str++;
   }
   *str = '\0';
}
1
  • 2
    The code compiled for me, I just got a runtime error. Unrelated to your problem, but whenever you use new you need a corresponding delete. In your case you need delete [] since you are allocating an array. Commented Apr 25, 2014 at 3:57

1 Answer 1

6

This part doesn't do what you think it does:

str1 = "This string";
add1 = " add this one";

You're attempting to assign a string literal ("This string") to a string pointer (str1). That won't work because:

  1. you've basically thrown away the pointers that you just allocated with new one line ago and
  2. string literals cannot be modified during run time (literals are of type const char [], so you should expect a compiler error/warning about this).

Hence, you're going to need to manually copy the string literal into your char array. You can use the standard library function strcpy for this (this requires <cstring>):

std::strcpy(str1, "This string");
std::strcpy(add1, " add this one");
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a different way to initialize a dynamic char array to say what I want (without using strcpy)? I just took that out, and the code runs fine, but the strings are randomly assined ASCII characters.
The one I showed is as simple as it gets. You could also write str1[0] = 'T'; str1[1] = 'h'; str1[2] = 'i'; str1[3] = 's'; str1[4] = ' '; ... and so on but I'm not sure you want to actually write that. Furthermore, if you run the code without initializing the array, then you are entering the territory of undefined behavior (not to mention, your string might not even be null-terminated if it's all garbage).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.