How to overwrite strings

So I am completely lost on what to do. I have two strings, one is longer than the other. If the second string is longer than the first string then I have to resize the first array and replace it with the longer substring. I can't use vectors. Please help, I'm so lost and I've been working on this assignment for weeks
Last edited on
int main()
{
char * str1 = new char[10];
char * str2 = new char[20];

memcpy(str1, "123456789", sizeof("123456789"));
memcpy(str2, "1234567891234", sizeof("1234567891234"));

if (strlen(str1) < strlen(str2))
{
char * tmp = new char[strlen(str2) + 1];
memcpy(tmp, str2,strlen(str2)+1);
delete[]str1;
str1 = tmp;
}
else
{
memcpy(str1,str2, strlen(str2) + 1);
}

std::cout << str1 << std::endl;
system("pause");
}
Use dynamic arrays. Google it if you don't know what it is. Or here: http://www.cplusplus.com/doc/tutorial/dynamic/
Last edited on
Aljasm wrote:
I can't use vectors

Can you use strings? Probably not since with strings it is trivial:

if(s2.size() > s1.size()) s1 = s2;
or, if you're supposed to replace the first with the second in any case, not just when the second is larger,
s1 = s2;
and if you can't use strings, it's worth explaining exactly what "I have two strings," means. Are they char arrays instead? Are they static, stack-allocated, or heap-allocated? Existing work-in-progress code would help get an answer relevant to your needs.

@ljzshuai there are more calls to new[] than calls to delete[] in your code
Last edited on
Topic archived. No new replies allowed.