C語言中指標和字串中的一些小結,指標字串小結

來源:互聯網
上載者:User

C語言中指標和字串中的一些小結,指標字串小結

<pre name="code" class="objc"><span style="font-family: Arial, Helvetica, sans-serif;">void a_A(char *str){</span>
for (int i =0; *(str+i) != '\0'; i++) { if (*(str+i) >= 'a' && *(str+i) <= 'z') { *(str+i) -= 32; } }


這是一個把字串中的字元轉化為大寫的函數

學指標的時候,我這樣定義:

    char *str ="hello wrold";
結果運行程式直接崩潰了,後來發現:

這是指向常量的不能修改,啟動並執行話會崩潰,也就是只允許讀,不允許寫


用數組的話就沒有問題:

char str1[]="hellllo world";

後來我又在考慮一個問題,怎麼執行複製的操作呢,我嘗試了如下代碼:

    char *a="hello world";    char b[]={0};    for (int i = 0; i < 20; i ++) {        b[i]=*(a+i);    }    puts(b);

結果還是崩潰了,用數組的話是沒有問題的

然後我想起字串的話C語言是有複製的方法的

strcpy(<#char *#>, <#const char *#>);

後面可以是常數,於是我執行了以下操作:

    char *a="hello world";    char b[]={0};    strcpy(b, a);    puts(b);

結果。。。還是程式崩潰

然後,繼續測試。。。

 char *a="hello world";    char b[]="hgashjgdsjhasjhas";    puts(strcpy(b, a));
然後,運行成功了,應該是b數組中要有>=a的記憶體才能得到a中的字元

照著這個方法我又返回來測試了自己寫的複製:

    char *a="hello world";    char b[]="hgashjgdsjhasjhas";//    strcpy(b, a);//    puts(b);        for (int i = 0; i < 20; i ++) {        b[i]=a[i];    }    puts(b);
結果運行是成功了的.

然後我再次測試(數組數組的複製):

    char b[] = "hgashjgdsjhasjhas";    char c[] = {0};//    strcpy(b, a);//    puts(b);          for (int i = 0; i < 20; i ++) {         c[i]=b[i];    }    puts(c);

結果運行成功

hgashjgdsjhasjhas


猜想:複製的時候,數組複製指標常量的時候不是會開闢記憶體的 

為驗證我的猜想,做了如下測試:c[],括弧裡面的值改變


    char *a = "hello world";    char c[20] = {0};//    strcpy(b, a);//    puts(b);    for (int i = 0; i < 20; i ++) {        c[i]=a[i];    }    puts(c);
運行成功。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.