[英]String concatenation using pointers
How do I achieve concatenation using only pointers since the code below gives (a segmentation fault) error (at runtime)? 由于下面的代码在运行时给出(分段错误)错误,我如何仅使用指针实现串联?
#include <stdio.h>
#include <string.h>
int main()
{
char *s1="Front";
char *s2="Back";
char *s3=strcat(s1,s2);
puts(s3);
return 0;
}
Because you are trying to write to a string literal. 因为您正在尝试写入字符串文字。 The line
char *s1 = "Front";
char *s1 = "Front";
points to a string constant, which can't be written to. 指向无法写入的字符串常量。
Change it to char s1[20] = "Front";
将其更改为
char s1[20] = "Front";
and it should work out like you expect - as long as you are adding no more than 14 characters. 只要您添加的字符数不超过14个,它的效果就会如您所愿。
阅读有关strcat
,并记住文字字符串(例如"Front"
和"Back"
)是不可修改的。
You need space for the result, like this: 您需要空间来存储结果,如下所示:
#include <stdio.h>
#include <string.h>
int main()
{
char *s1="Front";
char *s2="Back";
char s3[80];
s3[0] = '\0';
strcat(s3,s1);
strcat(s3,s2);
puts(s3);
return 0;
}
The code gives an error because concatenating s1
with s2
will require the allocated memory for s1
to be >= the combined lengths of the two byte arrays. 该代码给出了错误,因为将
s1
与s2
串联将需要为s1
分配的内存大于等于两个字节数组的组合长度。 strcat
will attempt to iterate over memory that wasn't assigned to s1
, thus causing a runtime error. strcat
将尝试遍历未分配给s1
内存,从而导致运行时错误。 The only way this will work through pointers is if you make str3
a char array where the size is known at compile time (or a pointer to a dynamically-allocated one for runtime): 通过指针工作的唯一方法是,将
str3
在编译时知道大小的char数组(或在运行时指向动态分配的指针的指针):
char s1[10] = "Front";
char *s2 = "Back";
char *s3 = strcat(s1, s2);
You can do it this way too. 您也可以这样做。 Though it is not better than strcat() but it is implemented using pointers only.
尽管它不比strcat()好,但是仅使用指针来实现。
#include<stdio.h>
#define SIZE 20
void concat(char *,char *);
int main()
{
char string1[SIZE]="\0",string2[SIZE]="\0";
printf("Enter String 1:\n");
gets(string1);
printf("Enter String 2:\n");
gets(string2);
concat(string1,string2);
return 0;
}
void concat(char *str1,char *str2)
{
char *conc=str1;
while(*str1!='\0')
str1++;
*str1=' ';
++str1;
while(*str2!='\0')
{
*str1=*str2;
str1++,str2++;
}
*str1='\0';
printf("Concatenated String:\n");
puts(conc);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.