#include <stdio.h>void copy_string(char from[],char to[]){ /* 1、while迴圈在實現時,由於str字元數組的後面有結束符'\0',因此巧妙地將這一條件作為複製是否結束的標誌。 2、C語言的while迴圈不同與Java的while迴圈,繼續迴圈的條件為非零,由於'\0'字元與整數的相通性,所以當為字串結束 標誌'\0'時,while停止迴圈 3、在使用數組傳遞參數時,傳遞的是指向這個數組的指標變數 */ printf("careful,%d\n",'\0'); while(*to++=*from++); // 注意這裡是"="號,而不是"=="號 return ;}void main(){ char str[]="this is a string!"; printf("%s\n",str); char dec_str[20]; copy_string(str,dec_str); printf("%s\n",dec_str); return ;}
最後在codeBlocks環境下運行後的結果如所示。
#include <stdio.h>void copy_string(char from[],char to[]){ /* 1、在為to參數傳遞指標變數時,並沒有為dec_str分配儲存單元 2、在改變to指標變數指向後,to指向了可用的記憶體單元,而dec_str還是保持了以前的指向 */ to=(char*)malloc(sizeof(char)*20);// 是為指標指向的目標變數分配記憶體的大小,如果超過了這個大小?? char *start_to=to; while(*to++=*from++); printf("copy_string函數:%s\n\n",start_to);}void main(){ char str[]="this is a st33333333333333ring!";//完全超過了20個字元的長度 printf("main函數:%s\n",str); char *dec_str; printf("copy_string函數調用前:%s\n",dec_str); copy_string(str,dec_str); printf("copy_string函數調用後:%s\n",dec_str); return ;}
程式啟動並執行結果如所示。