[英]Concatenation of two strings using pointers but it can not run
此代码想使用指针连接 2 个字符串,但无法运行。 它只运行 2 行,然后停止。
#include <stdio.h>
int main()
{
int i = 0, j = a0;
char *str1, *str2, *str3;
puts("Enter first string");
gets(str1);
puts("Enter second string");
gets(str2);
printf("Before concatenation the strings are\n");
puts(str1);
puts(str2);
while(*str1)
{
str3[i++] = *str1++;
}
while(*str2)
{
str3[i++] = *str2++;
}
str3[i] = '\0';
printf("After concatenation the strings are\n");
puts(str3);
return 0;
}
gets() 需要一个缓冲区来放入字符串,但您传递给它的是一个未初始化的指针。 此外,如前所述,您不应在新代码中使用它。 fgets(str, len, stdin) 会做同样的事情,但不会溢出缓冲区。
例子:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], str3[200];
puts("Enter first string: ");
fgets(str1, 100, stdin);
puts("Enter second string: ");
fgets(str2, 100, stdin);
printf("Before concatenation the strings are\n%s\n%s\n", str1, str2);
memset(str3, 0, 200);
strncat(str3, str1, 200);
strncat(str3, str2, 200);
printf("After concatenation the strings are\n%s\n", str3);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main(){
int i=0,j=0;
char *str1,*str2,*str3;
puts("Enter first string");
str1=malloc(50*sizeof(char));
str2=malloc(50*sizeof(char));
str3=malloc(50*sizeof(char));
gets(str1);
puts("Enter second string");
gets(str2);
printf("Before concatenation the strings are\n");
printf("%s\n",str1);
printf("%s",str2);
while(*str1){
str3[i++]=*str1++;
}
while(*str2){
str3[i++]=*str2++;
}
str3[i]='\0';
printf("\nAfter concatenation the strings are\n");
puts(str3);
return 0;
}
在这里,我为指针分配了内存,以便您的代码可以正常工作。
#include <stdio.h>
void concatStr(char* str1,char* str2,char* str3){
while(*str3++ = *str1++);
str3--;
while(*str3++ = *str2++);
}
int main()
{
char str1[100],str2[100],str3[200];
char *strp1,*strp2,*strp3;
printf("enter str 1\t");
scanf("%s",str1);
printf("enter str 2\t");
scanf("%s",str2);
printf("str1\t%s\n",str1);
printf("str2\t%s\n",str2);
concatStr(str1,str2,str3);
printf("%s",str3);
return 0;
}
你可以试试这个...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.