2017-06-04 67 views
-5
#include<stdio.h> 

/* a function to merge two strings */ 

void stringMerge(char* f, char* s){ 

while(*f++); 

while((*f++ = *s++)); 

} 

int main(){ 

char s1[] = "Hello "; 

char s2[] = "World"; 

stringMerge(s1,s2); 

printf("%s",s1); 

return 0; 

} 
+4

's1'具有6個字符的空間(7個字節與''\ 0'') ; 's2'有5個字符的空間(6個字節)。你沒有一個能夠保存11個字符的對象(12個字節用於「'\ 0'')。 – pmg

+1

@roch標準C函數strcat還是你自己寫的函數? –

+1

'while(* f ++);'==>'while(* f)f ++;'否則你會跳過字符串終止符而不是覆蓋它。 –

回答

-2

我建議你使用string.hstrncat()。這裏是你的代碼:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
int main(void){ 
    char *s1 = "Hello "; 
    char *s2 = "World\n"; 
    size_t s1_size = strlen(s1); 
    size_t s2_size = strlen(s2); 
    char *concat = calloc((s1_size + 1 + s2_size + 1), sizeof(char)); 
    if (concat == NULL) { 
     perror("Calloc"); 
     exit(EXIT_FAILURE); 
    } 
    strncat(concat, s1, s1_size); 
    strncat(concat, s2, s2_size); 
    printf("%s", concat); 
    free(concat); 
    return 0; 

} 
+0

'strncat(concat,s1,s1_size);'? 'concat'被*初始化*。 –

+0

什麼?我已經安裝了concat,然後是strncat。 –

+0

是的,但只是在我指出錯誤之後。你把'malloc'改成了'calloc'。 –

0

考慮到你要連接的字符串的聲明,那麼它似乎是你的意思是下面的函數實現。

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

char * stringMerge(const char *s1, const char *s2) 
{ 
    size_t n = strlen(s1); 

    char *p = (char *)malloc(n + strlen(s2) + 1); 

    if (p) 
    { 
     strcpy(p, s1); 
     strcpy(p + n, s2); 
    } 

    return p; 
} 


int main(void) 
{ 
    char s1[] = "Hello "; 
    char s2[] = "World"; 

    char *p = stringMerge(s1, s2); 

    puts(p); 

    free(p); 
} 

或下列

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

char * stringMerge(const char *s1, const char *s2) 
{ 
    size_t n = strlen(s1); 

    char *p = (char *)malloc(n + strlen(s2) + 1); 

    if (p) 
    { 
     char *t = p; 
     while (*t = *s1++) ++t; 
     do { *t = *s2++; } while (*t++); 
    } 

    return p; 
} 

int main(void) 
{ 
    char s1[] = "Hello "; 
    char s2[] = "World"; 

    char *p = stringMerge(s1, s2); 

    puts(p); 

    free(p); 
} 

在這兩個程序的輸出是

Hello World 
相關問題