指標數組-字串數組

來源:互聯網
上載者:User
Are you confused??

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

int main(){
    int cmpstringp(const void *p1, const void *p2);
   
    char *nations[5]={"china","america","australia","france","german"};
    int i;
    for(i=0;i<5;i++)
       printf("%s/n",nations[i]);
    qsort(nations,5,sizeof(nations[0]),cmpstringp);
    printf("/n/nafter sorting:/n/n");
    for(i=0;i<5;i++)
        printf("%s/n",nations[i]);
    return 0;
}

/* int strcmp(const char *s1, const char *s2);
*/
int cmpstringp(const void *p1, const void *p2)
       {
           /* The actual arguments to this function are "pointers to
              pointers to char", but strcmp() arguments are "pointers
              to char", hence the following cast plus dereference */

           return strcmp( *(char * const *)p1,*(char * const *)p2);
       }

 
字串在c中的定義是一個引用, 對存放連續字元記憶體區的一個引用。比如, 可以這樣定義:char *s = "hello";

s的實際值是一個地址值, 是int型。

一個指標數組就可以儲存一組字串, 如代碼中的nations。nations[i]就類似上面定義的s, 但nations[i]在函數qsort裡是作為一個數值型的地址,需要轉換成char *型: (char*)p1, 再以地址的形式傳到strcmp裡: *(char *)p1

 

聯繫我們

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