Reputation: 21
This throws an error id returned 1 error status. The loop is working but I cant print the final concatenated string. When i try to print the final string it does nothing.
char str1[50], str2[50], str[100];
char *p1, *p2, *p3;
int i = 0, j = 0;
p1 = &str1[0];
p2 = &str2[0];
p3 = &str[0];
printf("enter a string:");
gets(str1);
printf("enter a string:");
gets(str2);
while (i <= strlen(str1) + strlen(str2)) {
if (i != strlen(str1)) {
*(p3 + i) = *(p1 + i);
i++;
} else {
*(p3 + i) = *(p2 + j);
j++;
}
Upvotes: 0
Views: 68
Reputation: 16876
This check here is wrong:
if(i!=strlen(str1))
When i
is bigger than strlen(str1)
it will get false again, but it is supposed to stay true. Change it to this:
if (i < strlen(str1))
Furthermore, you're not increasing i
in the else
block. This is going to cause an endless loop with ever-growing j
, at least until the undefined behavior will cause your program to exit, possibly through an access violation. Try this instead:
else {
*(p3 + i) = *(p2 + j);
i++; // increase i in both cases
j++;
}
Or better yet, make it unconditional. For instance, you could take the i++
out of the body change the loop to this:
for (i = 0; i <= strlen(str1) + strlen(str2); i++)
Also, may I interest you in the array subscript notation? Instead of this:
if (i < strlen(str1)) {
*(p3 + i) = *(p1 + i);
}
Do this:
if (i < strlen(str1)) {
p3[i] = p1[i];
}
It's much cleaner this way and people who will work with your code will appreciate it.
Upvotes: 1