C語言之對(duì)于將二維數(shù)組作為參數(shù)傳遞的思考

這兩天在學(xué)習(xí)掃地僧的課程(二級(jí)指針三種內(nèi)存模型)時(shí),最后的作業(yè)是把“第一種內(nèi)存模型和第二種內(nèi)存模型的內(nèi)容復(fù)制到第三種內(nèi)存模型中彬向,并進(jìn)行排序”窑邦。老師預(yù)定義了前兩種內(nèi)存模型的內(nèi)容祟昭,和對(duì)應(yīng)的函數(shù)實(shí)現(xiàn)接口咧栗,如下:

    char *p1[] = { "aaaaa", "cccccc", "bbbbb" };
    char buf2[10][30] = { "111111", "3333333", "2222222" };

函數(shù)接口:

int sort(char ** myp1/*in*/, int num1/*in*/, char(*myp2)[30]/*in*/, int num2/*in*/, char ***myp3/*out*/, int *pNum3/*out*/);

既然老師希望在sort()函數(shù)解決問題臊恋,我的思路是:

  1. 先獲得傳入的兩個(gè)字符串?dāng)?shù)組中衣洁,最長的字符串長度;
  2. 取兩個(gè)輸入的字符串?dāng)?shù)組的成員數(shù)量之和抖仅,并且獲得最長的那個(gè)字符串的長度之后坊夫,根據(jù)這兩個(gè)參數(shù)再堆上申請(qǐng)空間;
  3. 分別復(fù)制兩個(gè)字符串?dāng)?shù)組到新的堆空間上撤卢;
  4. 針對(duì)堆空間的字符串?dāng)?shù)組進(jìn)行排序环凿,最后輸出排好序的字符串。
  5. 釋放申請(qǐng)的堆空間放吩。

思路還比較清晰智听,然后就自己實(shí)現(xiàn)代碼了。首先我自己定義的函數(shù)接口為:

// 獲取最長的字符串長度
int getRowLen(char **myp1/*in*/, int num1/*int*/, int *pLen)
// 申請(qǐng)堆空間
int getArray3(char ***p, int RowNum, int RowLen)
// 復(fù)制字符串?dāng)?shù)組
int copyArray(char **myp1/*in*/, int num1/*in*/, char **myp3/*in*/, int *pMyp3Row/*in, out*/)
// 釋放堆空間
int getArray3_Free(char ***p3, int p3num)
// 最后是題目給定的函數(shù)接口屎慢,主要功能在該函數(shù)中實(shí)現(xiàn)
int sort(char ** myp1/*in*/, int num1/*in*/, char(*myp2)[30]/*in*/, int num2/*in*/, char ***myp3/*out*/, int *pNum3/*out*/)

測試案例如下:

int main()
{
    int nRet = 0;
    char *p1[] = { "aaaaa", "cccccc", "bbbbb" };
    char buf2[10][30] = { "111111", "3333333", "2222222" };
    char **p3 = NULL;
    int len1, len2, len3, i = 0;

    len1 = sizeof(p1) / sizeof(*p1);
    len2 = 3;

    nRet = sort(p1, len1, buf2, len2, &p3, &len3);
    if (nRet != 0) {
        printf("func sort() err: %d \n", nRet);
        return nRet;
    }

    printf("after sorting...\n");
    for (; i < len3; i++) {
        printf("%s \n", p3[i]);
    }

    getArray3_Free(&p3, len3);
    system("pause");
}

在編譯的時(shí)候就遇到了困惑瞭稼,編譯器報(bào)錯(cuò):
Error C2664 'int copyArray(char **,int,char **,int )': cannot convert argument 1 from 'char ()[30]' to 'char **'
我在追溯問題的時(shí)候一直以為是指針傳輸?shù)膯栴},但是想不到更具體的可疑點(diǎn)腻惠。最后在做實(shí)驗(yàn)的時(shí)候發(fā)現(xiàn),有兩個(gè)函數(shù)接口有同樣的問題欲虚,getRowLen() 和 copyArray()都是把試圖原數(shù)組的地址傳進(jìn)來集灌,可是,每次傳入的數(shù)組是buf2[10]
[30]的時(shí)候就會(huì)報(bào)錯(cuò),原因在于:

設(shè)計(jì)的函數(shù)參數(shù)列表中沒有指定確定的維度信息欣喧,在傳輸buf2[10][30]的時(shí)候腌零,因?yàn)閟ort()指定了維度信息char(myp2)[30],所以編譯器知道m(xù)yp2的第二維是30個(gè)char類型的長度唆阿,至于myp2中有多少個(gè)字符串益涧,在傳入myp2的時(shí)候編譯器必然是已經(jīng)計(jì)算出myp2中包含的字符串的個(gè)數(shù)了。但是驯鳖,如果我們不指定清楚第二維的大小闲询,那么編譯器在分配空間時(shí)走到這里就會(huì)遇到一個(gè)“摩棱兩個(gè)”的問題:第二維是多大不知道,那么不論分配多少空間都是有可能“踩地址”的浅辙!*所以編譯器不得不在這里報(bào)錯(cuò)了扭弧。

知道了原因后,我不得不重新設(shè)計(jì)了函數(shù)接口如下记舆,明顯是比較笨拙的:

// 獲取最長的字符串長度
int getRowLen(char **myp1/*in*/, int num1/*int*/, int *pLen)
// 獲取最長的字符串長度:用于buf2
int getRowLen_1(char (*myp1)[30]/*in*/, int num1/*int*/, int *pLen)

// 申請(qǐng)堆空間
int getArray3(char ***p, int RowNum, int RowLen)

// 復(fù)制字符串?dāng)?shù)組
int copyArray(char **myp1/*in*/, int num1/*in*/, char **myp3/*in*/, int *pMyp3Row/*in, out*/)
// 復(fù)制字符串?dāng)?shù)組:用于buf2
int copyArray_1(char (*myp1)[30]/*in*/, int num1/*in*/, char **myp3/*in*/, int *pMyp3Row/*in, out*/)

// 釋放堆空間
int getArray3_Free(char ***p3, int p3num)

// 最后是題目給定的函數(shù)接口鸽捻,主要功能在該函數(shù)中實(shí)現(xiàn)
int sort(char ** myp1/*in*/, int num1/*in*/, char(*myp2)[30]/*in*/, int num2/*in*/, char ***myp3/*out*/, int *pNum3/*out*/)

這樣一來,就相當(dāng)于針對(duì)二級(jí)指針的第一種內(nèi)存模型和第二種內(nèi)存模型分別設(shè)計(jì)了函數(shù)接口泽腮,雖然功能實(shí)現(xiàn)了御蒲,可是畢竟有“重復(fù)造輪子”之嫌。

不過诊赊,通過繞一個(gè)彎我也深刻體會(huì)到了指針在C語言中帶來的便利之處删咱。假如在測試案例中,都這樣定義字符串?dāng)?shù)組:

buf0[3][30]  = { "aaaaa", "cccccc", "bbbbb" };
buf1[3][20] = { "111111", "3333333", "2222222" };
buf2[3][10] = { "hello", "world", "C Program Language" };

這樣在設(shè)計(jì)函數(shù)接口的時(shí)候豪筝,就必須為所有的二維長度設(shè)計(jì)好函數(shù)痰滋,這樣明顯很笨拙。但是如果是使用指針來定義字符串?dāng)?shù)組時(shí)续崖,不同的字符串?dāng)?shù)組就可以使用一套函數(shù)接口來工作了敲街。這樣才符合代碼簡潔之道!
YES POINTER!


以下是所有源代碼

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

int getArray3_Free(char ***p3, int p3num)
{
    int nRet = 0;
    int i = 0;
    char **pTmp = NULL;

    if (p3 == NULL) {
        nRet = -1;
        printf("func getArray3_Free:: detects that (p3 == NULL), error code: %d \n", nRet);
        goto END;
    }

    pTmp = *p3;
    if (pTmp == NULL) {
        nRet = -2;
        printf("func getArray3_Free:: detects that (pTmp == NULL), error code: %d \n", nRet);
        goto END;
    }

    for (; i < p3num; i++) {
        if (pTmp[i] != NULL) {
            free(pTmp[i]);
            pTmp[i] = NULL;
        }
    }

    free(pTmp);
    *p3 = NULL;
    goto END;

END:
    return nRet;
}
int getArray3(char ***p, int RowNum, int RowLen)
{
    int nRet = 0;
    int i = 0;
    char **pTmp = NULL;
    //int nLen = 60;

    if (p == NULL) {
        nRet = -1;
        printf("func getArray3:: detects that (p == NULL), error code: %d \n", nRet);
        goto END;
    }

    pTmp = (char **)malloc(sizeof(char *) * RowNum);
        if (pTmp == NULL) {
            nRet = -2;
            printf("func getArray3:: detects that (pTmp == NULL), error code: %d \n", nRet);
            goto END;
        }

    for (; i < RowNum; i++) {
        pTmp[i] = (char *)malloc(sizeof(char)  * RowLen);
    }
    *p = pTmp;
    goto END;

END:
    return nRet;
}
int getRowLen(char **myp1/*in*/, int num1/*in*/, int *pLen)
{
    int nRet = 0;
    int nLen = 0, nLenRow, i = 0;

    if (myp1 == NULL) {
        nRet = -1;
        printf("func getRowLen:: detectst that (myp1 == NULL), error code: %d \n", nRet);
        goto END;
    }

    for (; i < num1; i++) {
        nLenRow = strlen(myp1[i]) + 1;
        nLen = (nLenRow > nLen) ? nLenRow : nLen;
    }

    *pLen = nLen;
    goto END;

END:
    return nRet;
}
int getRowLen_1(char (*myp1)[30]/*in*/, int num1/*int*/, int *pLen)
{
    int nRet = 0;
    int nLen = 0, nLenRow, i = 0;

    if (myp1 == NULL) {
        nRet = -1;
        printf("func getRowLen:: detectst that (myp1 == NULL), error code: %d \n", nRet);
        goto END;
    }

    for (; i < num1; i++) {
        nLenRow = strlen(myp1[i]) + 1;
        nLen = (nLenRow > nLen) ? nLenRow : nLen;
    }

    *pLen = nLen;
    goto END;

END:
    return nRet;
}
int copyArray(char **myp1/*in*/, int num1/*in*/, char **myp3/*in*/, int *pMyp3Row/*in, out*/)
{
    int nRet = 0;
    int i = 0, myp3Row;
    char **pTmp = NULL;

    if (myp1 == NULL || myp3 == NULL || myp3 == NULL || pMyp3Row == NULL) {
        nRet = -1;
        printf("func sort:: detects that (myp1== NULL || myp3 == NULL || pNum3 == NULL || pMyp3Row == NULL), error code: %d \n", nRet);
        goto END;
    }

    pTmp = myp3;
    if (pTmp == NULL) {
        nRet = -2;
        printf("func sort:: pTmp == NULL), error code: %d \n", nRet);
        goto END;
    }

    myp3Row = *pMyp3Row;
    for (; i < num1; i++) {
        strncpy(pTmp[myp3Row], myp1[i], strlen(myp1[i]));
        pTmp[myp3Row][strlen(myp1[i])] = '\0';
        printf("pTmp[%d]: %s \n", myp3Row, pTmp[myp3Row]);
        myp3Row += 1;
    }

    *pMyp3Row = myp3Row;

END:
    return nRet;
}
int copyArray_1(char (*myp1)[30]/*in*/, int num1/*in*/, char **myp3/*in*/, int *pMyp3Row/*in, out*/)
{
    int nRet = 0;
    int i = 0, myp3Row;
    char **pTmp = NULL;

    if (myp1 == NULL || myp3 == NULL || myp3 == NULL || pMyp3Row == NULL) {
        nRet = -1;
        printf("func sort:: detects that (myp1== NULL || myp3 == NULL || pNum3 == NULL || pMyp3Row == NULL), error code: %d \n", nRet);
        goto END;
    }

    pTmp = myp3;
    if (pTmp == NULL) {
        nRet = -2;
        printf("func sort:: pTmp == NULL), error code: %d \n", nRet);
        goto END;
    }

    myp3Row = *pMyp3Row;
    for (; i < num1; i++) {
        strncpy(pTmp[myp3Row], myp1[i], strlen(myp1[i]));
        pTmp[myp3Row][strlen(myp1[i])] = '\0';
        myp3Row += 1;
    }

    *pMyp3Row = myp3Row;

END:
    return nRet;
}
int sort(char ** myp1/*in*/, int num1/*in*/, char(*myp2)[30]/*in*/, int num2/*in*/, char ***myp3/*out*/, int *pNum3/*out*/)
{
    int nRet = 0;
    int nLenRowMax1 = 0, nLenRowMax2 = 0, nLenRow = 0;
    int nRowIdx = 0;
    int i, j;
    char ** pTmp = NULL;
    char *pTmpCg = NULL;

    if (myp1 == NULL || myp2 == NULL || pNum3 == NULL) {
        nRet = -1;
        printf("func sort:: detects that (myp1== NULL || myp2 == NULL || pNum3 == NULL), error code: %d \n", nRet);
        goto END;
    }

    *pNum3 = num1 + num2;     // to get the size of string group 3
#if (0)
    *myp3 = (char**)malloc(sizeof(char *) * sizeof(*pNum3));    // to ask address for myp3
    if (myp3 == NULL) {
        nRet = -2;
        printf("func sort:: detects that (myp3 == NULL), error code: %d \n", nRet);
        goto END;
    }
#endif
    nRet = getRowLen(myp1, num1, &nLenRowMax1);

    if (nRet != 0) {
        nRet = -3;
        printf("func sort:: detects that (nRet != 0), error code: %d \n", nRet);
        goto END;
    }
    printf("nLenRowMax1: %d \n", nLenRowMax1);

    nRet = getRowLen_1(myp2, num2, &nLenRowMax2);
    if (nRet != 0) {
        nRet = -4;
        printf("func sort:: detects that (nRet != 0), error code: %d \n", nRet);
        goto END;
    }
    nLenRow = (nLenRowMax1 > nLenRowMax2) ? nLenRowMax1 : nLenRowMax2;  // to get the row size of new array
    nRet = getArray3(myp3, *pNum3, nLenRow);    // to put space for myp3
    if (nRet != 0) {
        nRet = -4;
        printf("func sort:: detects that (nRet != 0), error code: %d \n", nRet);
        goto END;
    }

    nRet = copyArray(myp1, num1, *myp3, &nRowIdx);
    if (nRet != 0) {
        nRet = -5;
        printf("func sort:: detects that (nRet != 0), error code: %d \n", nRet);
        goto END;
    }

    nRet = copyArray_1(myp2, num2, *myp3, &nRowIdx);
    //nRet = copyArray(myp2, num2, *myp3, &nRowIdx);
    if (nRet != 0) {
        nRet = -5;
        printf("func sort:: detects that (nRet != 0), error code: %d \n", nRet);
        goto END;
    }

    printf("before sorting: \n");
    for (i=0; i < *pNum3; i++) {
        printf("%s \n", (*myp3)[i]);
    }

    if (nRowIdx != *pNum3) {
        *pNum3 = nRowIdx - 1;
        printf("111111111111111111");
    }
    //*******sort********
    pTmp = *myp3;
    for (i = 0; i < *pNum3; i++) {
        for (j = i + 1; j < *pNum3; j++) {
            if (strcmp(pTmp[i], pTmp[j]) > 0) {
                pTmpCg = pTmp[i];
                pTmp[i] = pTmp[j];
                pTmp[j] = pTmpCg;
            }
        }
    }
    goto END;

END:
    return nRet;
}
int main()
{
    int nRet = 0;
    char *p1[] = { "aaaaa", "cccccc", "bbbbb" };
    char buf2[10][30] = { "111111", "3333333", "2222222" };
    char **p3 = NULL;
    int len1, len2, len3, i = 0;

    len1 = sizeof(p1) / sizeof(*p1);
    len2 = 3;

    nRet = sort(p1, len1, buf2, len2, &p3, &len3);
    if (nRet != 0) {
        printf("func sort() err: %d \n", nRet);
        return nRet;
    }

    printf("after sorting...\n");
    for (; i < len3; i++) {
        printf("%s \n", p3[i]);
    }

    getArray3_Free(&p3, len3);

    printf("hello world....\n");
    system("pause");
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末严望,一起剝皮案震驚了整個(gè)濱河市多艇,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌像吻,老刑警劉巖峻黍,帶你破解...
    沈念sama閱讀 221,820評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異拨匆,居然都是意外死亡姆涩,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門惭每,熙熙樓的掌柜王于貴愁眉苦臉地迎上來骨饿,“玉大人,你說我怎么就攤上這事『曜福” “怎么了绒北?”我有些...
    開封第一講書人閱讀 168,324評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長察署。 經(jīng)常有香客問我闷游,道長,這世上最難降的妖魔是什么贴汪? 我笑而不...
    開封第一講書人閱讀 59,714評(píng)論 1 297
  • 正文 為了忘掉前任脐往,我火速辦了婚禮,結(jié)果婚禮上嘶是,老公的妹妹穿的比我還像新娘钙勃。我一直安慰自己,他們只是感情好聂喇,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,724評(píng)論 6 397
  • 文/花漫 我一把揭開白布辖源。 她就那樣靜靜地躺著,像睡著了一般希太。 火紅的嫁衣襯著肌膚如雪克饶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評(píng)論 1 310
  • 那天誊辉,我揣著相機(jī)與錄音矾湃,去河邊找鬼。 笑死堕澄,一個(gè)胖子當(dāng)著我的面吹牛邀跃,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蛙紫,決...
    沈念sama閱讀 40,897評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼拍屑,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了坑傅?” 一聲冷哼從身側(cè)響起僵驰,我...
    開封第一講書人閱讀 39,804評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎唁毒,沒想到半個(gè)月后蒜茴,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡浆西,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,431評(píng)論 3 340
  • 正文 我和宋清朗相戀三年粉私,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片室谚。...
    茶點(diǎn)故事閱讀 40,561評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡毡鉴,死狀恐怖崔泵,靈堂內(nèi)的尸體忽然破棺而出秒赤,到底是詐尸還是另有隱情猪瞬,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評(píng)論 5 350
  • 正文 年R本政府宣布入篮,位于F島的核電站陈瘦,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏潮售。R本人自食惡果不足惜痊项,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,928評(píng)論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望酥诽。 院中可真熱鬧鞍泉,春花似錦、人聲如沸肮帐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽训枢。三九已至托修,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間恒界,已是汗流浹背睦刃。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留十酣,地道東北人涩拙。 一個(gè)月前我還...
    沈念sama閱讀 48,983評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像耸采,于是被迫代替她去往敵國和親兴泥。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,573評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 指針是C語言中廣泛使用的一種數(shù)據(jù)類型洋幻。 運(yùn)用指針編程是C語言最主要的風(fēng)格之一郁轻。利用指針變量可以表示各種數(shù)據(jù)結(jié)構(gòu); ...
    朱森閱讀 3,449評(píng)論 3 44
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,111評(píng)論 1 32
  • __block和__weak修飾符的區(qū)別其實(shí)是挺明顯的:1.__block不管是ARC還是MRC模式下都可以使用文留,...
    LZM輪回閱讀 3,329評(píng)論 0 6
  • 1.寫一個(gè)NSString類的實(shí)現(xiàn) +(id)initWithCString:(c*****t char *)nu...
    韓七夏閱讀 3,772評(píng)論 2 37
  • 七燥翅、數(shù)組 在C語言中骑篙,數(shù)組屬于構(gòu)造數(shù)據(jù)類型。數(shù)組根據(jù)元素的類型不同森书,數(shù)組又可以分為 數(shù)值數(shù)組 靶端、字符數(shù)組 谎势、指針數(shù)...
    堅(jiān)持到底v2閱讀 826評(píng)論 0 2