Click here to Skip to main content
15,894,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Merge two strings. I found the length of two strings and trying to merge them using the below loop.

Char s1 [20],s2 [20];
Int i=0;
Int k, len1,len2; //len1 and len2 are lengths of 2 strings

For (k=len1;k <len1+len2;k++)
{
s1 [k] = s2 [i];
++i;
}

I got correct output but 4 garbage values are also appended in the end. Reasons pls.

What I have tried:

I found another loop for the same.
For (i=0;i <len2;i++)
{
s1 [len1+i] = s2 [i];
}

But i wanted to know the error in my program.
Thanks
Posted
Updated 23-Jul-18 23:18pm

As OriginalGriff says, you need to terminate your string properly thus:
C++
For (k=len1;k <len1+len2;k++) 
{
s1 [k] = s2 [i];
++i;
} 
s1[k] = '\0'; // add the terminating null to the end of the array

You should also check that len1 + len2 is less than 20.
 
Share this answer
 
Comments
Member 13922884 24-Jul-18 13:08pm    
Thank you. It worked. But i have a doubt.
The length of two strings i am taking is 4 and 7. So total is 11. Then why is it taking only 4 garbage values. Should it not display garbage values upto 20 counting i.e. 9.
Richard MacCutchan 24-Jul-18 15:09pm    
When you allocate a variable (whether a single item or array) the compiler makes a note of its relative address (starting at zero) and its length. The name of the item is the first (or only) element that is allocated. The next variable that you create will be given an address following the previous one. But these addresses are known only to the compiler in order to generate the correct address references in your code. If you decide to write 100 items in an array that was defined as holding only 20 then it is your problem, the compiler cannot prevent you from doing that. Similarly if you add fewer items than the maximum, then neither the compiler nor the run time libraries will know that. So when you try to print a character array that does not have a terminating null character, the library function will continue to display characters until it finds a null. So if a character array of size 20 contain 11 valid characters but does not have a null at position 11 (0-10 being valid), then it will continue to try and print until it finds a null. That could be at offset 15, or even offset 50,000.
Richard MacCutchan 24-Jul-18 15:13pm    
That is because the print function will keep printing characters until it finds a null character. Since you have only added 11 characters to the array, then whatever was in the remaining portion of memory before will be printed. If a null character is found four characters beyond your data, then that is where it will stop. If it is not found until 4000 characters beyond, then you will have a nice lot of garbage printed. When you allocate a 20 character array it is up tp you to manage that space correctly. The compiler and run time libraries do not manage it for you.
Member 13922884 25-Jul-18 12:49pm    
Ok, got that. Thanks a lot.
Quite a few reasons.
The first one is that you are trying to append two strings of equal length - 20 characters each - into the space allocated for one of them. If both len1 and len2 values add up to less than 20, you don't have a problem. But if they exceed that, then you are "running off the end" of one array or the other, and that's a problem because you don't know what memory you are using, so you don't know what you are overwriting. The compiler isn't going to tell you, and there is no standard that will define that because it's a bad, bad idea to do it in the first place! Define an output string area that is big enough to hold both strings, plus an extra character.

That extra character leads us to the second reason: strings in C are just an array of characters, terminated with a character containing a null value - '\0'
Since you don't copy or add a '\0' to the end of your output, when you print the string, it doesn't stop printing characters until it reaches a memory location that just happens to contain null. Hence you get a random number of random characters printed after your expected data.
 
Share this answer
 
Comments
Member 13922884 23-Jul-18 14:16pm    
That was the maximum limit i gave. I am not exceeding the 20 limit.
Try
#include <stdio.h>

// merges strings 's1', 's2' into bufer 'buf', having size 'bufsize'
// returns 0 on success.
int merge( const char * s1, const char * s2, char * buf, size_t bufsize)
{
  const char * sa[2] = {s1,  s2 };

  size_t i = 0;
  size_t k = 0;
  for ( i = 0; i<2; ++i)
  {
    const char *p = sa[i];
    while ( *p )
    {
      if ( k == bufsize) return -1;
      buf[k] = *p;
      ++k;
      ++p;
    }
  }
  if ( k == bufsize) return -1;
  buf[k] = '\0';
  return 0;
}

// usage example
int main()
{
  const char * s1 = "foo";
  const char * s2 = "bar";
  char m[20];
  int rc = merge(s1, s2, m, sizeof(m));
  if (  rc )
    printf("unable to merge\n");
  else
    printf("merged string '%s'\n", m);

  return 0;
}
 
Share this answer
 
Comments
Member 13922884 23-Jul-18 16:48pm    
Thanks for your response. But i am just a beginner and have not reached upto pointer till now.
I wanted to know error in my code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900