0

I wrote the following code for string concatnation using pointers in C

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void strCat(char *str1,char *str2);
int main(void)
{
char str1[] = "Rohit";
char str2[] = "Kumar";  
strCat(str1,str2);
return 0;
}

void strCat(char *str1,char *str2)
{
int i;
char *start;
start = str1;
printf("%s",str1);
while(*str1++ != '\0')
    continue;
while(*str2 != '\0')
    *str1++ = *str2++;
*str1 = '\0';

printf("%s\n",str1);
}

Why the ouput is Rohit(null). Please Help!!

1
  • 1
    I really hope you just did this to learn stuff and not for any real code (there are functions like strcat). Commented Jul 11, 2011 at 9:15

5 Answers 5

5

Well, first of all str1 isn't long enough to fit both strings.

Here

while(*str2 != '\0')
    *str1++ = *str2++; /* You are overstepping str1 -> undefined behavior */

There are other problems with the code. Perhaps you should try the string.h strcat instead ?

Sign up to request clarification or add additional context in comments.

Comments

1

You are modifying the str1 pointer, and setting it to "\0" at the end, and then printing NULL. I think this is what you need:

void strCat(char *str1,char *str2)
{
int i;
char *start;
printf("%s",str1);
while(*str1++ != '\0')
    continue;
start = str1;
while(*str2 != '\0')
    *str1++ = *str2++;
*str1 = '\0';

printf("%s\n",start);
}

Also, as someone else noted, str1 isn't big enough to hold both strings.

Comments

1
while(*str1++ != '\0')
    continue;
while(*str2 != '\0')
    *str1++ = *str2++;

In the first loop, you loop till *str==0. And when it finally happens, you still increment str1 leaving the '\0' as it was.

This is more correct:

while(*str1++ != '\0');
--str1;
while(*str2 != '\0')
    *str1++ = *str2++;

Comments

0

You're doing a dangerous thing. str1 and str2 are fixed-size arrays, and str1 doesn't have enough space for the content you're copying into it. The result leads to undefined behavior.

Comments

0

As you are printing str1, it will have null value because you have incremented the str1 pointer till the end and stored the null value.

when you print str1, it is pointing to null hence printing null

Comments

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.