2013-08-21 72 views
-5

使用strcat函數時出現問題。我沒有idea.please幫助me.thanks使用strcat與strcpy發生問題

char dst[5]="hello"; 
char *a = "12345"; 
char *b = "54321"; 

//work 
strcat(strcpy(dst, a), b); 
printf("one==%s\n",dst); 

//error 
strcpy(dst, a); 
strcat(dst, b); 
printf("two==%s\n",dst); 
+0

你只是幸運的是,第一個案件工作。 –

+1

@Dayalrai這種「幸運」會導致衛星崩潰,並在條件改變時人們死亡。 –

+0

「幸運」是什麼意思? –

回答

0

的問題,這兩個版本是你寫的過去dst結束。 ab都需要六個字節,包括NUL終止符; dst只有五個空間。

這導致undefined behaviour

未定義行爲的本質是這樣的,它可能會或可能不會表現出來。如果是這樣,它可能會以相當任意的方式進行。

0

你不正確地分配你的DST指針你的記憶,這裏是一個工作代碼:

int    main() 
{ 
    char *dst; 
    char *a = strdup("12345"); 
    char *b = strdup("54321"); 

    dst = malloc(100); 
    dst = strdup("hello");                    
strcat(strcpy(dst, a), b); 
printf("one==%s\n",dst);                     
strcpy(dst, a); 
strcat(dst, b); 
printf("two==%s\n",dst); 
} 
+0

處理'char'時,不需要'(sizeof(* dst))'; C標準明確定義了'char'的大小爲1. – verbose

+0

你是對的,修正了 – Saxtheowl

0

方案:

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

int main() 
{ 
     char dst[15]="hello"; 
     char *a = "12345"; 
     char *b = "54321"; 

     //work 
     strcat(strcpy(dst, a), b); 
     printf("one==%s\n",dst); 

     //error 
     strcpy(dst, a); 
     strcat(dst, b); 
     printf("two==%s\n",dst); 
     return 0; 
    } 

OUTPUT:

# 1: hide clone input 8 seconds ago 
result: success  time: 0s memory: 2684 kB  returned value: 0 

input: no 
output: 
one==1234554321 
two==1234554321 

編輯: 而不是15你可以使用11以及..希望你明白你的代碼的目的..

+0

你確實可以使'dst'小於'15',但它應該至少有'11'個字符來解釋最終的' 0' – Virgile

+0

謝謝@Virgile .. – Abhishek

+0

我的意思是當dst的大小是5時,strcat(strcpy(dst,a),b)正在工作,爲什麼? –