station
station

Reputation: 7145

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(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!!

Upvotes: 0

Views: 5580

Answers (5)

user2484633
user2484633

Reputation: 27

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

Upvotes: 0

littleadv
littleadv

Reputation: 20272

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.

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133014

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

Upvotes: 1

cnicutar
cnicutar

Reputation: 182649

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 ?

Upvotes: 5

Blazes
Blazes

Reputation: 4779

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.

Upvotes: 1

Related Questions