开发者

String concatenation using pointers in C!

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开发者_Go百科(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!!


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 ?


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.


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++;


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜