[英]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.