简体   繁体   English

使用 C 中的指针进行字符串连接!

[英]String concatenation using pointers in C!

I wrote the following code for string concatnation using pointers in C我使用 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) .为什么输出是Rohit(null) Please Help!!请帮忙!!

Well, first of all str1 isn't long enough to fit both strings.好吧,首先str1的长度不足以容纳两个字符串。

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?也许您应该尝试使用string.h strcat代替?

You are modifying the str1 pointer, and setting it to "\0" at the end, and then printing NULL.您正在修改str1指针,最后将其设置为“\0”,然后打印 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.此外,正如其他人指出的那样, str1 不足以容纳两个字符串。

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

In the first loop, you loop till *str==0 .在第一个循环中,您循环直到*str==0 And when it finally happens, you still increment str1 leaving the '\0' as it was.当它最终发生时,您仍然会增加str1 ,而保留'\0'原样。

This is more correct:这更正确:

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

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.当您打印 str1 时,它将具有 null 值,因为您已将 str1 指针递增到末尾并存储了 null 值。

when you print str1, it is pointing to null hence printing null当您打印 str1 时,它指向 null 因此打印 null

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. str1str2是固定大小的 arrays,而str1没有足够的空间容纳您要复制到其中的内容。 The result leads to undefined behavior.结果导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM