我試圖在不使用任何函式的情況下將兩個字串與指標連接在一起。當我輸入這兩個字串時,例如首先是 hello 然后是 world 輸出是
你好
世界
而不是 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);
}
uj5u.com熱心網友回復:
該程式具有未定義的行為,因為您沒有為輸入的字串分配記憶體。
char *s=(char *)malloc(sizeof(char *));
char *s2=(char *)malloc(sizeof(char *));
fgets(s,10,stdin);
fgets(s2,10,stdin);
sizeof(char *)您只為兩個指標 ( )分配了記憶體。
您需要分配足夠大的記憶體,以便在第一個字符陣列中包含輸入的字串及其連接。
該函式fgets可以將換行符 '\n' 附加到輸入的字串中。你需要覆寫它。
此外,您不應該更改原始指標,因為您需要使用它們來釋放分配的記憶體。
并考慮到結果字串將至少包含11字符,包括終止零字符'\0'而不是10字符,如果您要輸入"hello"并"world"連接它們。雖然一般來說,如果輸入的字串不包含換行符,最好保留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 );
}
程式輸出可能是
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 ) );
陣列初始化為零以保持空字串,以防 fgets 的呼叫被中斷。
uj5u.com熱心網友回復:
fgets()讀取到檔案末尾或行尾,但在讀取的資料中包含行尾。
因此,在您的情況下,您還將字串與新行連接起來。
另一方面,您的陳述句char *s=(char *)malloc(sizeof(char *));
是為sizeof(char*)字符分配記憶體,即:指標的大小,而不是 X 個字符。
此外,由于您要連接一個 10 個字符的字串,因此需要分配字串以至少保存該字串(20 個字符 1 個空值)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467397.html
