繁体   English   中英

C 连接两个字符串的程序

[英]C program to concatenate two strings

我试图在不使用任何函数的情况下将两个字符串与指针连接在一起。例如,当我输入两个字符串时,首先是 hello 然后是 world output 是

你好

世界

而不是 helloworld。任何帮助将不胜感激。

#include<stdio.h>
#include<stdlib.h>
int main(){
char *s=(char *)malloc(sizeof(char *));
char *s2=(char *)malloc(sizeof(char *));
fgets(s,10,stdin);
fgets(s2,10,stdin);
int i=0;
while(*s){
    s++;
    i++;

}
while(*s2!='\0'){
    *s=*s2;
    s++;
    s2++;
    i++;
}
*s='\0';
printf("%s",s-i);
}

该程序具有未定义的行为,因为您没有为输入的字符串分配 memory。

char *s=(char *)malloc(sizeof(char *));
char *s2=(char *)malloc(sizeof(char *));
fgets(s,10,stdin);
fgets(s2,10,stdin);

您只为两个指针 ( sizeof(char *) ) 分配了 memory 。

您需要分配足够大的 memory,以便在第一个字符数组中包含输入的字符串及其连接。

function fgets可以将换行符'\n' append 转换为输入的字符串。 你需要覆盖它。

此外,您不应更改原始指针,因为您需要使用它们来释放分配的 memory。

并考虑到如果您要输入"hello""world"并将它们连接起来,结果字符串将至少包含11字符,包括终止零字符'\0'而不是10字符。 虽然一般情况下,如果输入的字符串不包含换行符,最好保留13字符。

该程序可以通过以下方式查找示例

#include <stdlib.h>
#include <stdio.h>

int main( void )
{
    enum { N = 7 };
    char *s1 = malloc( 2 * N - 1 );
    char *s2 = malloc( N );
    s1[0] = '\0';
    s2[0] = '\0';

    fgets( s1, N, stdin );
    fgets( s2, N, stdin );

    char *p1 = s1;

    while (*p1 != '\n' && *p1 != '\0') ++p1;

    for (char *p2 = s2; *p2 != '\n' && *p2 != '\0'; ++p2)
    {
        *p1++ = *p2;
    }

    *p1 = '\0';

    puts( s1 );

    free( s1 );
    free( s2 );
}

程序 output 可能是

hello
world
helloworld

而不是这些线

char *s1 = malloc( 2 * N - 1 );
char *s2 = malloc( N );
s1[0] = '\0';
s2[0] = '\0';

你可以写

char *s1 = calloc( 2 * N - 1, sizeof( char ) );
char *s2 = calloc( N, sizeof( char ) );

arrays 被零初始化以保留空字符串,以防 fgets 的调用被中断。

fgets()读取到文件末尾或行尾,但在读取的数据中包括行尾。

因此,在您的情况下,您还将字符串与新行连接起来。

另一方面,您的声明char *s=(char *)malloc(sizeof(char *)); 正在为sizeof(char*)个字符分配 memory 即:指针的大小,而不是 X 个字符。

此外,由于您将一个 10 个字符的字符串与另一个字符串连接起来,因此需要分配该字符串以至少容纳该字符串(20 个字符 + 1 个空值)。

暂无
暂无

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

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