C指標與函數的關係

來源:互聯網
上載者:User
#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 ;}

程式啟動並執行結果如所示。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.